Wednesday, March 02, 2011

FluentNHibernate: "unable to locate persister:"

There's quite a bit of info out there for this error message, but all I could find refers to xml configuration, the recommendation being somewhere along the lines of:


  1. Make sure your mapping file is named *.hbm.xml
  2. Make sure it is set to an embedded resource.
  3. If all else fails, debug.

What most articles fail to mention is the root cause, which is the fact that NHibernate was not able to load the mappings for the class you are trying to use in your query, knowing that you can at least focus in a single area, in the case of fluent nhibernate, the configuration looks something like this:


public static ISessionFactory CreateSessionFactory() {
   return Fluently.Configure()
   .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("AppDb")))
   .Mappings(m => m.FluentMappings.Add<ProductMap>())
   .Mappings(m => m.FluentMappings.Add<CategoryMap>())
   .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
   .BuildSessionFactory();
}

The two .Mappings() lines are the bug in this case, any subsequent calls to it override the first one and you won't be able to query Products
There are two ways of fixing this, one you can tell it to load all the mappings found on the same assembly as the first map


   .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductMap>())

or if you want to be specific:


   .Mappings(m => { m.FluentMappings.Add<ProductMap>();
                    m.FluentMappings.Add<CategoryMap>(); })


Hope someone else finds this helpful

No comments: