Archive

Archive for August, 2011

NHibernate Mapping tester

August 29, 2011 2 comments

When using NHibernate, you often need to check if your mappings matches the model and database. Using frameworks like FluentNHibernate usually helps form the compilation perspective, because your mappings won’t compile if there’s any misspelled property or class. But for convensions and database schemas, it’s possible to have a mismatch.
The following code is a test that will check every property on every mapped class and then every collection. Basically, it queries each type and each collection so NHibernate needs to create the sql statement and execute it. If any error is thrown, you will notice.

[Test]
public void AllMappingsAreOk()
{
	var session = GetCurrentNHibernateSession();
	var errors = new List<string>();

	foreach (var entry in session.SessionFactory.GetAllClassMetadata())
	{
		var type = entry.Key;
		var data = entry.Value;

		try
		{
			session.CreateCriteria(type).SetMaxResults(0).List();
		}
		catch (Exception e)
		{
			errors.Add(string.Format("Error getting type {0}: {1}", type, e.Message));
		}

		foreach (var collection in data.PropertyNames.Where(x => data.GetPropertyType(x).IsCollectionType))
		{
			try
			{
				session.CreateCriteria(type).CreateCriteria(collection).SetMaxResults(0).List();
			}
			catch (Exception e)
			{
				errors.Add(string.Format("Error getting collection {0}.{1}: {2}",
										 type,
										 collection,
										 e.Message));
			}
		}
	}
	Assert.True(errors.Count == 0, string.Join(Environment.NewLine, errors));
}

This piece of code was really helpful in the past and is following me in every project involving NHibernate. It seemed useful to share 🙂