Wednesday, November 16, 2011

NHibernate loquacious mapping config

Edit 2012/01/21: added some overloads to retrieve assemblies metadata loaded. This can be useful in many way, my one is the ability to serialize NHibernate configuration, like explained here.





I just publish a very small project for who uses NHibernate: it allows to use the web.config or app.config of your application to set up what assemblies load for the mapping in the "conformist" way.
For who doesn't know it, NHibernate is probably the best ORM for .NET existing on the way: and it's open source.
Loquacius mapping is the new "mapping by code" way introduced in 3.2 that basically comes from Fabio Maulo’s ConfORM.
Here's the link of the project: https://github.com/michelelepri/NHibernate.LoquaciousMappingConfig

How to set up all:
  1. download and compile de project;
  2. add to your .config file a section to the configSection node like this:
    <section
       name="loquaciousNHibernateMapping"
       type="NHibernate.LoquaciousMappingConfig.Config.LoquaciousNHibernateMappingSection, NHibernate.LoquaciousMappingConfig"/>
    
  3. add the configuration containing the list of your assemblies:
    <loquaciousNHibernateMapping>
          <assemblies>
             <add assembly="YourAssebly"/>
          </assemblies>
       </loquaciousNHibernateMapping>
    
  4. call the extended method to read the configuration and load the assemblies:
    var cfg = new Configuration().Configure();
    
    // your other coded config stuff
    
    var mapper = new ModelMapper();
    mapper.AddFromConfig(); // here the lib extended method
    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
    cfg.AddDeserializedMapping(mapping, "yourDocumentName");
    var sessionFactory = cfg.BuildSessionFactory(); 
All done !

I found it very useful in my (quite big) project to use both FluentNHibernate and the mapping-by-code cause I would like to migrate all the maps to the loquacious one.
Simply add these lines of code after the cfg.AddDeserializadMapping(..)  and replace the SessionFactory build:

// reuse the same cfg object with the mapping by code just added
var sessionFactory = Fluently.Configure(cfg)
    .Mappings(x => x.FluentMappings.AddFromAssemblyOf<YourClass>() /* or the method you like */)
    .BuildSessionFactory();

So you will have both fluent and loquacious mapping in your projects.

Happy coding! :)

No comments:

Post a Comment