Home > C#, NHibernate > NHibernate Mapping tester

NHibernate Mapping tester

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 🙂

Advertisements
  1. December 1, 2013 at 3:47 am

    Oh, man. This is exactly what I was looking for and I knew deep down that it could be done. It just test the mappings and that’s all I want. Thank you for this.

  1. December 1, 2013 at 4:02 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: