【问题标题】:Mapping all derived types of a generic type in one table在一个表中映射泛型类型的所有派生类型
【发布时间】:2019-10-25 16:48:36
【问题描述】:

我有一个关于 EF Core 2.1 的问题

我有一个基本类型,我们将其命名为CustomerCustomerOldCustomerNew 是从它派生而来的。这些自动存储在一个表中,到目前为止一切顺利。

现在我有了一个泛型类型,用于将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&lt;T&gt; 的所有派生类型存储在同一个表中?如何定义DbSets&lt;&gt;

【问题讨论】:

  • OldCustomer 和 NewCustomer 类型是否来自同一个表?
  • 是的,他们做到了!这是由 ef core 自动完成的

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


【解决方案1】:

您的看起来是映射模式 TPH(每个层次结构的类型)的一个很好的候选对象。 您可以阅读更多关于该主题的here

【讨论】:

  • 谢谢。我对 tph 知之甚少,但您的帖子澄清了一些事情:我真正的问题应该是:当父类型是泛型时如何实现 TPH?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2012-09-08
  • 2021-08-04
  • 2014-03-22
  • 1970-01-01
相关资源
最近更新 更多