繁体   English   中英

EF Core 5 TPT - 继承了具有不同 ID 名称的 object

[英]EF Core 5 TPT - Inherited object with different ID name

通常应用程序是用 ID 字段构造的,只是在数据库中将其命名为“ID”。 但是在我工作的应用程序中不遵循这个约定。 我有两个表,标准化为用 inheritance 表示。 主表称为“Entity”,其主键称为“IdEntity”。 而另一个从Entity继承的表称为“Source”,其主键称为“IdSource”,但它不是身份,是Entity.IdEntity的外键。

在当前应用程序(webforms)中它工作正常,我需要在一个新的应用程序上用 EF Core 和 .NET Core 5 表示它。如果我用 _context.Entities.Find(id) 列出它工作正常,但同样不是当我做 _context.Sources.Find(id) 时适用。

我的课程定义为:

实体

public class Entity
{
    [Column("IdEntity"), Key]
    public int Id { get; set; }
}

资源

public class Source : Entity
{
    [Column("IdSource"), Key]
    public int Id { get; set; }
}

请注意,我在 Source 中明确指定了 ID 列。 但是,当我对代码运行查询时,我收到错误消息:“Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'IdEntity'.'”

我使用 SQL Server Profiler 跟踪执行情况,并意识到 EF 正在创建查询,只是忽略了来自 Source 的列 header IdSource并插入IdEntity ,创建如下内容:

select * -- All fields
from Entity t
inner join Source t0 on t.IdEntity = t0.IdEntity 
/* Note that it is inserting t0.IdEntity, but the alias for t0 is for Source, that there are no fields named IdEntity */

如何明确告诉 EF Core 主键是 IdSource 而不是 IdEntity for Source?

编辑:这个新应用程序是数据库优先的,它是强制性的。 我正在尝试从基于 Webforms 的现有应用程序迁移。

尝试使用流畅的 API配置 model

这样您就可以轻松地为每个实体 class 执行类似此代码的操作:

    public class SourceEntityTypeConfiguration : IEntityTypeConfiguration<Source>
    {
        public void Configure(EntityTypeBuilder<Source> builder)
        {
            builder
                .Property(b => b.Id)
                .HasColumnName("IdSource");               
        }
    }

我不确定这个问题是否仍然与您相关,但也许这些信息会有所帮助: https://github.com/dotnet/efcore/issues/19811 简而言之,具有不同 ID-column-names 的 TPT 尚不可能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM