派生类在EntityFramework Core中不生成表

问题

EntityFramework Core版本是3.1.

public class Test: Entity
{
    public string Name { get; set; }
}
public class Test2:Test
{
    public string Add { get; set; }
}

DbContext

public DbSet<Test> Tests { get; set; }
public DbSet<Test2> Test2s { get; set; }
public AbcDbContext(DbContextOptions<AbcDbContext> options)
    : base(options)
{
}

但是只生成了基类的表。
派生类在EntityFramework Core中不生成表_第1张图片
派生类并没有生成我需要的表 Test2s,且对应的属性成了基类的column。

解决方法

后来用

modelBuilder.Entity().ToTable("TestInherits");

出现错误
The entity type 'Test2' cannot be mapped to a table because it is derived from 'Test'. Only base entity types can be mapped to a table.

很好,这个错误很清晰了。google该错误。

Starting with EF Core 3.0 and in preparation for adding TPT and TPC support in a later release, ToTable() called on a derived type will now throw an exception to avoid an unexpected mapping change in the future.

从EF Core 3.0开始,为在以后的版本中添加TPT和TPC支持做准备,在派生类型上调用的ToTable()现在将引发异常,以避免将来发生意外的映射更改。

totable-on-a-derived-type-throws-an-exception

EF数据库映射策略 –

  • Table Per Hierarchy (TPH)
    • 一张表用于表示层次结构中的所有类。 “区分符”列用于区分不同的类型。该表默认使用基类的名称或其关联的DbSet属性。
  • Table Per Concrete Type (TPC)
    • 单独的表用于表示继承链中的每个具体类型。任何抽象基本类型的属性都将作为每个具体类型表中的字段生成。不同类型之间没有关系。
  • Table Per Type (TPT)
    • 单独的表用于表示继承链中的每种类型,包括抽象类型。表示派生类型的表通过外键与其基本类型相关

对比可知,我需要的是TPC!!

但是进一步查询到:

EF Core 尚不支持 EF6 支持每种类型一个表(TPT)和每个具体的表类型(TPC)。 TPT 是为 EF Core 5.0 计划的主要功能。
https://docs.microsoft.com/zh-cn/ef/core/modeling/inheritance

目前,EntityFramework core最新版本是3.1.6.所以没办法解决。

我注意到新生成的一列Discriminator。可以用这个字段将我们需要的数据筛选出来。

参考

https://stackoverflow.com/questions/59558083/the-entity-type-customer-cannot-be-mapped-to-a-table-because-it-is-derived-fro

https://datatellblog.wordpress.com/2015/04/12/inheritance-modelling-patterns-with-entity-framework-6-code-first/

https://www.learnentityframeworkcore.com/inheritance

你可能感兴趣的:(派生类在EntityFramework Core中不生成表)