Is it possible to get a list of all mapped objects from NHibernate IStatelessSession or ISession?

I am trying to write a test for NHibernate mappings that will automatically pick up and validate all new mappings that are added.

At the moment I have a test that opens a session to a known test database, then tries to load the first object of each type and asserts that it is not null.

This all works fine, but it means that every time I add a new entity mapping, I need to remember to update the test.

So what I want to do is check the mappings and try to load one of each of the mapped objects, but the NHibernate config object from which the sessionfactory is created does not appear in my test, so I was wondering is the way to access the list of mapped objects from the session or do I need to display the original config instead?

+3


source to share


3 answers


You can get SessionFactory from Session and SessionFactory has GetAllClassMetadata () method that returns IClassMetadata list. And from IClassMetadata you can get MappedClass (GetMappedClass ())

But you need some extra work to get the subclasses. This code might help:



var metaData = this.session.SessionFactory.GetClassMetadata(baseClass);
if (metaData != null && metaData.HasSubclasses)
{
    foreach (string entityName in ((NHibernate.Persister.Entity.IEntityPersister)metaData).EntityMetamodel.SubclassEntityNames)
    {
        var metadata = this.session.SessionFactory.GetClassMetadata(entityName);
        result.Add(metadata.GetMappedClass(EntityMode.Poco));
    }
}    

      

+5


source


I expose a config object and do a mapping that queries all my entities like this. It will output all errors from each of my mappings .:



[TestMethod()]
public void AllNHibernateMappingsAreOkay()
{
    bool failed = false;
    log4net.Config.XmlConfigurator.Configure();

    using (ISession session = SessionFactory.GetCurrentSession())
    {
        foreach (var s in SessionFactory.GetConfig().ClassMappings)
        {
            try
            {
                SessionFactory.GetCurrentSession().CreateQuery(string.Format("from {0} e", s.MappedClass.Name))
                    .SetFirstResult(0).SetMaxResults(50).List();
            }
            catch (Exception ex)
            {
                failed = true;
                log.ErrorFormat("\r\n\r\n {0} \r\n {1} \r\n\r\n", ex.Message, ex.InnerException.Message);   
            }
        }
    }

    Assert.IsFalse(failed, "One or more mappings have errors in them.  Please refer to output or logs.");
}

      

+2


source


if you only have one line for each object you can send session.QueryOver<object>().List();

0


source







All Articles