Search code examples
c#nhibernatenhibernate-mapping

NHibernate 4.0 code mapping with intentional duplicate import


How can I get this working using only NHibernate 4.0 and CoC?

I need to map two different classes that share the same name:

namespace MyApp.VersionA {
    public class User{
    //omitted properties
    }
}
namespace MyApp.VersionB {
    public class User{
    //omitted properties
    }
}

This is my NHibernate setup method:

var config = new Configuration();
config.Configure();
var mapper = new ModelMapper();
mapper.AddMappings(GetAllMappingTypes());
config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
config.BeforeBindMapping += (sender, args) => args.Mapping.autoimport = false;
Factory = config.BuildSessionFactory();

Notice that I set up autoimport=false, but I still get an DuplicateMappingException from NHibernate:

nhibernate.duplicatemappingexception: duplicate import:
User refers to both
MyApp.VersionA,
... and
MyApp.VersionB.User,
... (try using auto-import="false")


Solution

  • Alexander, try this:

            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name.Contains(".Infrastructure"));
            foreach (var assembly in assemblies)
            {
                var mapper = new ModelMapper();
                mapper.AddMappings(assembly.GetExportedTypes()
                    .Where(t => t.BaseType != null && t.BaseType.IsGenericType &&
                                t.BaseType.GetGenericTypeDefinition() == typeof (ClassMapping<>)));
    
                var compileMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
                compileMapping.autoimport = false;
    
                configuration.AddMapping(compileMapping);
            }