【问题标题】:FluentNHibernate AutoPersistenceModel with Interface referencesFluentNHibernate AutoPersistenceModel 与接口引用
【发布时间】:2010-12-13 10:14:58
【问题描述】:

我是第一次尝试 FluentNHibernate AutoPersistenceModel。让一个基本示例正常工作非常简单,但我在使它适合我的工作方式时遇到了问题。我通常使用接口,以便我的实体都实现一个接口并通过它们的接口引用所有相关实体,而不是它们的具体类型。给定以下类:

public Interface IFoo { }

public Interface IBar { IFoo Foo { get; set; } }

public Class Foo : IFoo { }

public Class Bar : IBar
{
     public IFoo Foo { get; set; }
}

我会有以下映射:

public class BarMapping : ClassMap<Bar>
{
    public AnswerMapping()
    {
        References<Foo>( x => x.Foo ).Column( "FooId" ).Cascade.None();
    }
}

如何使用 AutoPersistenceModel 实现相同的效果?我简要了解了 Conventions 和 ReferenceConvention 构建器,但没有任何文档或示例,我一直在苦苦挣扎。

编辑

我现在已将此与我的其他 SO post 一起将集合映射到接口转换为博客文章: http://bronumski.blogspot.com/2011/01/making-fluent-nhibernate-automapper.html

【问题讨论】:

    标签: c# .net nhibernate interface fluent-nhibernate


    【解决方案1】:

    经过一番挖掘,我想出了一个解决方案。有一个 IReferenceConvention 接口,我已经在其他示例中看到过该接口,但未涵盖此场景。通过实现接口并进行自定义约定,我能够使用 AutoPersistenceModel 实现与使用 ClassMap 相同的功能。

    public class ReferenceConvention : IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            Type instanceType = instance.Class.GetUnderlyingSystemType();
            if (instanceType == typeof(IFoo))
            {
                instance.CustomClass<Foo>();
            }
    
            instance.Cascade.All();
        }
    }
    

    更通用的方法可能是:

    public class ReferenceConvention : IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            Type instanceType = instance.Class.GetUnderlyingSystemType();
    
            if (instanceType.IsInterface)
            {
                // Assuming that the type starts with an I get the name of the concrete class
                string className = instanceType.Name.Substring( 1 );
    
                instance.CustomClass(instanceType.Assembly.GetType(
                    instanceType.FullName.Replace( instanceType.Name, className )));
            }
    
            instance.Cascade.All();
        }
    }
    

    还有一个我还没有看过的 ReferenceConventionBuilder,但这可能是一个更清洁的解决方案。

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多