4

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!

Karl Cassar
  • 6,043
  • 10
  • 47
  • 84

1 Answers1

7

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.

Rippo
  • 22,117
  • 14
  • 78
  • 117
  • Thanks a lot! I am using NH3.3, and found out that 'CompileMappingForAllExplicitlyAddedEntities' is an extension method found in `NHibernate.Mappings.ByCode` working on an `IEnumerable`. It is not found directly in the `ModelMapper`, as listed above. Unfortunately, there is a 'Serialize' method in the same `MappingsExtensions` file in the NH source code that is not public. I've copied the code into my general code base, so that I don't have to touch the NH code base. I will repost my solution below due to length. – Karl Cassar May 15 '12 at 14:19
  • Sorry my fault - didn't notice the last one was `AsString` and not `ToString`! That work's brilliantly, and really thanks for your very fast reply! – Karl Cassar May 15 '12 at 14:23
  • Just have to finally say, how many times I was here to copy paste that. Blody fantastic answer ;) – Radim Köhler Oct 23 '14 at 12:52