Ef Core 3 实体类型 XOrder 无法映射到 table,因为它派生自 Order Only base entity types can be mapped to a table

Ef Core 3 The entity type XOrder cannot be mapped to a table because it is derived from Order Only base entity types can be mapped to a table

Problem: We have Order entity with some inherit types such as : OnlineOrder , OfflineOrder , ...

public class Order 
{
    public Order()
    {
    }
    public virtual string Type { get; protected set; }
    public string Title { get; set; }
    public string Email { get; set; }
    public string Description { get; set; }
    public byte[] RowVersion { get; set; }

    public ICollection<OrderDetail> Details { get; set; }
}

public class OnlineOrder : Order
{
    public const string TypeName = "Online";
    public OnlineOrder() : base()
    {
    }
    public override string Type { get; protected set; } = TypeName;
    public OnlineType OnlineType { get; set; }
    public long FactorId { get; set; }
    public bool IsConfirmed { get; set; } = false;
}

public class OfflineOrder : Order
{
    public const string TypeName = "Offline";
    public OfflineOrder() : base()
    {
    }
    public override string Type { get; protected set; } = TypeName;
    public InputType InputType { get; set; }
    public long StoreId { get; set; }
}

并在所有实体的配置中使用此代码:

public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
    builder.ToTable(typeof(TEntity).Name, Schema);
}

但是当 运行 迁移时出现此异常:

The entity type 'OffineOrder' cannot be mapped to a table because it is derived from 'Order'. Only base entity types can be mapped to a table.

基于 this issue and this breaking change in ef core 3 ToTable() 抛出异常,因为(基于中断更改 link):

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.

所以我们更改配置 class:

public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
    if (typeof(TEntity).BaseType == null)
        builder.ToTable(typeof(TEntity).Name, Schema);
}

我现在通过调用 modelBuilder.Entity().ToTable(null);

解决了这个问题

另一个原因是在子实体(从另一个实体继承)上使用 SetTableName。参见 this issue