抽象中间类的NHibernate(Fluent)映射

本文关键字:Fluent 映射 NHibernate 中间 抽象 | 更新日期: 2023-09-27 18:28:35

我有一个通用对象类型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; }

感谢您的帮助。提前谢谢。

抽象中间类的NHibernate(Fluent)映射

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

FluentHibernate-自动映射忽略属性

因此,我们应该引入这种配置,并对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;
    }
}

这将使"位置"属性在默认情况下不被映射。下一步,是在需要的地方使用显式映射。。。