在一个表中映射泛型的所有派生类型

时间:2019-06-11 09:36:48

标签: c# entity-framework-core-2.1

我对EF Core 2.1有疑问

我有一个基本类型,我们将其命名为Customer,从中派生CustomerOldCustomerNew。到目前为止,它们都自动存储在一张表中。

现在,我具有将Customer映射到Product的通用类型:

public class CustomerToProduct<T> where T : Customer 
{ 
    public int CustomerId { get; set; }
    public T Customer { get; set; }
    public int ProductId { get; set; }
    public Product Product { get; set; }
    ...
}

CustomerToProduct的派生类型没有特定的属性。我只想使用它们,例如我通过属性CustomerToProduct.Customer访问的客户属于派生类型。

我在DbContext中为派生类型定义了DbSet,如下所示,这当然导致了单独的表:

public class MyDbContext : DbContext 
{
    public DbSet<OldCustomerToProduct> OldCustomerToProducts { get; set; }
    public DbSet<NewCustomerToProduct> NewCustomerToProducts { get; set; }
    ...
}

如何在同一表中存储CustomerToProduct<T>的所有派生类型?如何定义DbSets<>

1 个答案:

答案 0 :(得分:0)

您看起来像是映射模式TPH(每个层次结构的类型)的理想候选人。 您可以阅读有关该主题的更多here

相关问题