0

Is it possible to distribute a NHibernate-by-Code-Mapping over several classes?

E.g.

public class EntityMap1 : ClassMapping<Entity> {
  Id(x => x.Id);
  Property(x => x.PropertyOne);
}

public class EntityMap2 : ClassMapping<Entity> {
  Property(x => x.PropertyTwo);
}

I tried it but the mapping of PropertyTwo was missing in the generated HBML. Is there some way to achieve this?

Test
  • 3
  • 3

2 Answers2

0

I don't believe NHibernate would be able to compile both together to create a singular mapping. If the goal is to use a different set of mappings in one app versus another, you need to simply create two different mappings. If the goal is to have subclasses, there is a SubclassMapping interface you can extend.

Edit:

In looking over my notes, an extension to my answer about creating a different set of mappings would be the case where you have some feature plugged into your app that needs a different (sometimes more, sometimes less involved) mapping. To do this you need to have NHibernate generate them separately and add them to the configuration separately. Using conventions, this creates two separate sets of mappings (which contain some overlapping, but differently mapped, entites) that are plugged into one configuration:

NHibernateConfiguration.BeforeBindMapping += (sender, args) => args.Mapping.autoimport = false;

            var pluginMappings = new PluginMapper().Mappings;

            foreach (var hbmMapping in pluginMappings)
                NHibernateConfiguration.AddDeserializedMapping(hbmMapping, "PluginModel");

            var mainAppMappings = new AppMapper().Mappings;

            foreach (var hbmMapping in mainAppMappings)
                NHibernateConfiguration.AddDeserializedMapping(hbmMapping, "AppModel");
Fourth
  • 9,163
  • 1
  • 23
  • 28
  • Thanks. The goal was that a plugin can modify the mapping, i.e. EntityMap1 would reside in the main application and EntityMap2 in the plugin. Solved this issue by modifying the generated XML using Linq to XML (see my answer for code). – Test Mar 05 '12 at 18:05
0

As described in my comment to Fourth's answer the goal was that a plugin can modify the mapping of the main application, i.e. EntityMap1 would reside in the main program and EntityMap2 in the plugin. I could avoid this problem by only keeping EntityMap1 and manually modifying the generated XML.

var domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
var oldMappingXml = domainMapping.AsString();
var newMappingXml = ModifyMappings(oldMappingXml);
configuration.AddXmlString(newMappingXml);

oldMappingXml contains the XML generated by the mappings defined in the main application and ModifyMappings adds the changes required by the plugin. This is possible because the changes required by the plugins are well defined and follow the same algorithm for all plugins.

Test
  • 3
  • 3