Search code examples
c#nhibernatenhibernate-mapping-by-code

nhibernate HbmMapping to Xml


I am using NHibernate mapping-by-code to map the classes.

Sometimes, in order to debug my NHibernate configuration, I would require to check exactly what were the settings passed over to NHibernate, and it is quite difficult do debug the mapping-by-code.

Is there any way where you could convert the generated HbmMapping, back into the Xml file, just as if typed by hand?

This would help a lot in diagnosing if the problem is lying from my mappings!


Solution

  • Option 1

    Be warned this will write the XML into your BIN folder causing the IIS pool to recycle, so run once and then comment the WriteAllXmlMapping line back out!

    var mapper = new ModelMapper();
    mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
    
    //This will write all the XML into the bin/mappings folder
    mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();
    

    Option 2

    This will give you a a single large XML file that you can add a breakpoint to.

    var mapper = new ModelMapper();
    mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
    
    //you could add a breakpoint here! 
    var mappingXml = mapping.AsString();
    

    The source is from a blog post I wrote a while ago.