NHibernate Mapping: Creating Sanity Checks

time to read 5 min | 872 words

Here is a very easy way to find out if your database schema is still the same one that NHibernate expects:

[Test]

public void AllNHibernateMappingAreOkay()

{

   ISessionManager sessionManager = IoC.Resolve<ISessionManager>();

   using (ISession session = sessionManager.OpenSession())

   {

       IDictionary allClassMetadata = session.SessionFactory.GetAllClassMetadata();

       foreach (DictionaryEntry entry in allClassMetadata)

       {

           session.CreateCriteria((Type) entry.Key)

                .SetMaxResults(0).List();

       }

   }

}

This issues selects on all the mapped classes, so it will fail if the database is not in the expected sharep.

As a test, it is pretty rough, but it can find the missing column / table issues very quickly.