[英]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.