NHibernate(Fluent)映射抽象中间类

时间:2014-10-31 00:48:25

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

我有一个通用对象类型Entity和一些可以与Entity相关的类,例如EntityDescription和EntityLocation(多对一关系)。

实体类:

public class Entity
{
    public virtual Int64 ID { get; set; }
    // and other properties
}

EntityDescription类:

public class EntityDescription 
{
    public virtual Int64 ID { get; set; }
    public virtual Entity Entity { get; set; }
    public virtual String Description { get; set; }
    // and other properties
}

EntityLocation类:

public class EntityLocation 
{
    public virtual Int64 ID { get; set; }
    public virtual Entity Entity { get; set; }
    public virtual String Location { get; set; }
    // and other properties
}

有许多更具体的实体类型,例如公司,供应商,员工等 为了使事情更有趣,EntityDescription适用于所有特定类型,但只能为某些类型分配位置(EntityLocation仅适用于某些类型)。

如何在Fluent-NHibernate中映射这些类,以便EntityLocation列表仅在某些可以拥有位置的特定类(例如公司和供应商)上公开,而不是在通用的Entity类上公开?

// This property can exist in Entity
public virtual IList<EntityDescription> Descriptions { get; set; }

// I want this property to only exist in some specific types, not in Entity
public virtual IList<EntityLocation > Locations { get; set; }

任何帮助表示赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我想说,我们需要的是ShouldMap设置。检查这个答案:

FluentNHibernate - Automapping ignore property

因此,我们应该使用Locations属性的不同默认处理来引入此配置:

public class AutoMapConfiguration : DefaultAutomappingConfiguration
{
    private static readonly IList<string> IgnoredMembers = 
                        new List<string> { "Locations"}; // ... could be more...

    public override bool ShouldMap(Member member)
    {
        var shouldNotMap = IgnoredMembers.Contains(member.Name);

        return base.ShouldMap(member) && !shouldNotMap;
    }
}

这将使Locations属性默认为 NOT 映射。下一步是在需要的地方使用显式映射......

相关问题