NHibernate 4.0代码映射与故意重复导入

时间:2016-01-13 21:02:48

标签: c# nhibernate nhibernate-mapping

如何仅使用NHibernate 4.0和CoC

来实现此功能

我需要映射两个共享相同名称的不同类:

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

这是我的NHibernate设置方法:

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();

请注意,我设置了autoimport = false,但我仍然从NHibernate获得了DuplicateMappingException:

  

nhibernate.duplicatemappingexception:重复导入:
  用户指的是两个   MyApp.VersionA,
  ......和   MyApp.VersionB.User,
  ...(尝试使用auto-import =“false”)

1 个答案:

答案 0 :(得分:1)

亚历山大,试试这个:

        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);
        }