首页 > 解决方案 > Ef Core 3 实体类型 XOrder 不能映射到表,因为它是从 Order 派生的 只有基本实体类型可以映射到表

问题描述

问题:我们有带有一些继承类型的 Order 实体,例如: 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.

标签: c#entity-frameworkasp.net-core.net-coreef-core-3.0

解决方案


基于此问题和 ef core 3 中的此重大更改ToTable()引发异常,因为(基于重大更改链接):

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

所以我们改变配置类:

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

推荐阅读