【问题标题】: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 tableEf Core 3 实体类型 XOrder 不能映射到表,因为它是从 Order 派生的 只有基本实体类型可以映射到表
【发布时间】:2020-04-21 23:30:41
【问题描述】:

问题:我们有带有一些继承类型的 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-framework asp.net-core .net-core ef-core-3.0


    【解决方案1】:

    基于 ef core 3 中的 this issuethis breaking change 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);
    }
    

    【讨论】:

    • 那么,您知道 EF Core 3.0(或者在我的情况下为 3.1.1)是否支持 TPT 和 TPC?根据我目前的问题,情况似乎并非如此。
    • EF Core 仅支持 TPH(每层级表)。 TPT 支持是 EF Core 5.0 (docs.microsoft.com/en-us/ef/core/modeling/inheritance) 计划的主要功能。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我现在通过调用 modelBuilder.Entity().ToTable(null); 解决了这个问题

      【讨论】:

      • 这不是一个解决方案,而是一个 hack/workaround,请不要这样做。
      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多