Monday 25 July 2011

View the xml generated when mapping by code

When using mapping by code it may not be 100% obvious what XML is being generated for NHibernate.

You have a couple of options, the first option is to tell NHibernate to write all your mappings into the bin folder:-
var mapper = new ModelMapper();
mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());

//This will write all the XML into the bin/mappings folder
mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();

The second option is to use the extension method .AsString(). However you will be presented with one large XML blob.
var mapper = new ModelMapper();
mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
//you could add a breakpoint here! 
var mappingXml = mapping.AsString();
Either way you will be able to quickly and easily view the XML that is being injected into NHibernate. This is very useful for debugging or if you are upgrading all your hbm.xml files into the new mapping by code syntax and wish to compare like for like.

2 comments:

  1. Great post! If you get the chance, check out http://nuget.org/List/Packages/Nvergent

    ReplyDelete
  2. I should also mention that using the first option .WriteAllXmlMapping() will force an application refresh and it is possible to get into a infinite loop!

    ReplyDelete