如何在Fluent NHibernate中使用ConventionBuilder设置实体的ID

时间:2015-04-30 08:39:09

标签: c# fluent-nhibernate fluent-nhibernate-mapping

我遵循流畅的配置

var sessionFactory = Fluently.Configure()
                             .Database(configuration)
                             .Mappings(arg =>
                             {
                                 var autoMap = AutoMap.Source(typeSource);
                                 foreach (var convention in typeSource.GetConventions())
                                 {
                                     autoMap.Conventions.Add(convention);
                                 }
                                 autoMap.BuildMappings();
                             })
                             .BuildSessionFactory();

我使用的typeSource实例(FluentNHibernate.ITypeSource)也有GetConventions方法,返回System.Collections.Generic.IEnumerable<FluentNHibernate.Conventions.IConvention>

然后GetConventions的结果将被注入Conventions的{​​{1}}(在FluentNHibernate.Automapping.Automap - 流畅配置的方法中)。

Mappings的具体实现看起来像

GetConventions

我还想介绍一个基于public override System.Collections.Generic.IEnumerable<FluentNHibernate.Conventions.IConvention> GetConventions() { yield return FluentNHibernate.Conventions.Helpers.ConventionBuilder.Property.When( arg => arg.Expect(f => f.Type == typeof (string)), arg => arg.CustomType<CUSTOMTYPE>() ); } 注入ID的约定,我试图这样做:

EntityType

那么,我如何在ConventionBuilder中注入ID,也可能注入CombinedID?

编辑:

我也试过这个,但遗憾的是,应用路径(yield return FluentNHibernate.Conventions.Helpers.ConventionBuilder.Class.When( arg => arg.Expect(f => f.EntityType == typeof (ENTITYTYPE)), arg => arg.Id // does not work, as .Id is readonly ); )中的断点永远不会到达:

var a = 1;

1 个答案:

答案 0 :(得分:0)

我通过扩展Mappings - 稍微调用一下来解决了这个问题:

.Mappings(arg =>
{
    var autoPersistenceModel = AutoMap.Source(typeSource);
    foreach (var overrideType in typeSource.GetOverrideTypes())
    {
        autoPersistenceModel.Override(overrideType);
    }
    foreach (var conventionType in typeSource.GetConventionTypes())
    {
        autoPersistenceModel.Conventions.Add(conventionType);
    }
    arg.AutoMappings.Add(autoPersistenceModel);
})

不幸的是,这远非优雅或完整 - 如果AutoMap.Source(typeSource)能够处理来自GetTypes方法的约定和覆盖,或者IIdConvention会被考虑在内,那将会更加体面建立地图(它不是atm)......