"Import" by code ClassMapping to Fluent NHibernate

本文关键字:quot Fluent NHibernate to by Import code ClassMapping | 更新日期: 2023-09-27 18:18:11

我想为NHibernate使用NHibernate.Asp.Identity库,我想扩展标准的IdentityUser类-然而,在这个库中编写的所有映射都是用ByCode.Conformist.ClassMapping<>完成的。是否有任何方法可以"导入"这些映射(可能在数据库配置期间?),所以我可以像这样映射我的ApplicationUserIdentity与Fluent:

public class ApplicationUserIdentityMap : ClassMap<ApplicationUser>
{
     public ApplicationUserIdentityMap()
     {
          HasMany(x => x.MyProp);
          ...
     }
}

其中ApplicationUser为:

public class ApplicationUser : IdentityUser
{
    ... my properties
}

和到IdentityUser的映射用ByCode.Conformist.ClassMapping<>

"Import" by code ClassMapping to Fluent NHibernate

我想说,这应该不是一个问题。我们最后需要的是 Configuration 对象——提供了来自Fluent和Mapping-by-code(甚至更多)映射1)。基于这些资源:

  • 流利配置
  • NHibernate 3.2 Mapping by Code - Basic Mapping

可以是这样的配置:

// standard Fluent configuration
var fluentConfig = FluentNHibernate.Cfg.Fluently.Configure()
    .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
        .ConnectionString(@"Data Source=.;Database=TheCoolDB;Trusted_Connection=yes;"))
    .Mappings(m =>
        m.FluentMappings
            .AddFromAssemblyOf<MyAwesomeEntityMap>());
// return the NHibernate.Cfg.Configuration
var config = fluentConfig
    .BuildConfiguration();
// now Mapping by Code
// firstly the Mapper
var mapper = new NHibernate.Mapping.ByCode.ModelMapper();
mapper.AddMappings(Assembly
    .GetAssembly(typeof(IdentityUser)) // here we have to get access to the mapping
    .GetExportedTypes());
// finally the mapping just read
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
// extend already existing mapping
config.AddDeserializedMapping(mapping, null);
// the ISessionFactory
var factory = config.BuildSessionFactory();
扩展:

不知道如何混合流畅和映射的代码为目的的继承…

但有更狭窄的方式如何配置fluently和注入一些mapping-by-code的部分:

// Let's start with mapping-by-code,
// so firstly create the Mapper
var mapper = new NHibernate.Mapping.ByCode.ModelMapper();
mapper.AddMappings(Assembly
    .GetAssembly(typeof(IdentityUser)) // here we have to get access to the mapping
    .GetExportedTypes());
// create the mapping
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
// standard Fluent configuration
var fluentConfig = FluentNHibernate.Cfg.Fluently.Configure()
    .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
        .ConnectionString(@"Data Source=.;Database=TheCoolDB;Trusted_Connection=yes;"))
    .Mappings(m =>
        m.FluentMappings
            .AddFromAssemblyOf<MyAwesomeEntityMap>())
// here we INJECT the HBM mapping
// via call to built in ExposeConfiguration(Action<Configuration> config)
     .ExposeConfiguration(c => c.AddDeserializedMapping(mapping, null));
// the ISessionFactory
var factory = fluentConfig
    .BuildSessionFactory();