流畅的API EF继承和映射

时间:2014-06-02 15:18:53

标签: c# entity-framework inheritance fluent

我有一个系统,其中包含多个具有一对多关系的自引用实体(父子)。我想为所有这些实体使用公共基类:

public class SelfReferencing
{
  public SelfReferencing Parent {get; set;}
  public ICollection<SelfReferencing> Children {get; set;}
}

并从SelfReferencing继承特定实体。 在尝试执行以下操作时,Fluent API映射要求引用属性为定义类型:

modelBuilder.Entity<ConcreteSelfReferencing>()
                .HasMany(e => e.Children)
                .WithOptional(e => e.Parent);

那么,你能帮助我找到利用继承并获取映射实体的可能性吗?

THX

1 个答案:

答案 0 :(得分:4)

  

注意:下面的示例称为Table-Per-Hierarchy (TPH) - 即所有包含在一个表中。单击this link for Table-Per-Type (TPT),其中每种类型都有不同的表格。

使用基类型和继承类型时,必须告诉EF如何确定特定继承类型的关联。

拿你的代码:

public abstract class SelfReferencing
{
    public SelfReferencing Parent { get; set; }
    public ICollection<SelfReferencing> Children { get; set; }
}

public class ConcreteSelfReferencing : SelfReferencing
{
}

EF现在必须确定子类是ConcreteSelfReferencing还是任何其他类型的子类。这是由表本身上的鉴别器决定的,列不是映射的一部分。

再举一个例子,类似于我过去使用的:

public abstract class Policy
{
   public int Id { get; set; }
   public string PolicyNumber { get; set; }
}

public class InsurancePolicy : Policy
{
}

public class CarPolicy : Policy
{
}

表的结构如下:

| Id    |   PolicyNumber  | Type  |  ..... |
  1         CAR0001         C
  2         ISN0001         I

要让EF正确地得到它们,你会得到:

public class MyContext : DbContext
{
   public MyContext() : base()
   {
   }

   public DbSet<Policy> Policies { get; set; }

   protected override void OnModelCreating(ModelBuilder builder)
   {
      var policyMap = modelBuilder.Entity<Policy>();

      // Set up discriminators
      policyMap.Map<InsurancePolicy>(p => o.Requires("Type").HasValue("I"))
               .Map<CarPolicy>(p => o.Requires("Type").HasValue("C"));

      // Notice that `Type` is only used for the discriminators, not an actual
      // mapped property
      policyMap.HasKey(x=>x.Id);
      policyMap.Property(x=>x.PolicyNumber);
   }
}

从您的代码中,您可以自己进行过滤,也可以将过滤放在DbContext中。这是一个单独的类的例子。

public class PolicyRepository
{
   private MyContext context = new MyContext();

   public PolicyRepository()
   {
   }

   public IQueryable<InsurancePolicy> GetInsurancePolicies()
   {
      return this.context.Policies.OfType<InsurancePolicy>();
   }

   public IQueryable<CarPolicy> GetCarPolicies()
   {
      return this.context.Policies.OfType<CarPolicy>();
   }
}