![](/img/trans.png)
[英]multiple 1 to 0..1 relationships to the same Primary Key on parent table in entity framework Core
[英]Entity Framework - Multiple 1 to 0..1 relationships using the same Key
我已經閱讀了有關該主題的盡可能多的帖子,但是我嘗試過的所有解決方案似乎都無效。 我有一個現有數據庫,並從現有數據庫項目創建了一個新的Code First。
我有一個稱為Thing的基表。 每個對象在該表中都有一條記錄,使用Id作為唯一主鍵。 每個其他對象都繼承自此對象,但是它們在子表中使用相同的ID,而不在子表中使用新的Identity列。 有效地為每個“事物”賦予唯一的ID:
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Car
{
public int Id { get; set; }
//other properties
}
public class Person
{
public int Id { get; set; }
//other properties
}
public class Color
{
public int Id { get; set; }
//other properties
}
每個新記錄都首先在“事物”中創建一個項,然后使用該Id值在其各自的表中創建一個新記錄,從而創建多個1到0..1關系,其中派生表上的Id字段也是Thing的FK。
從1到0..1的車
事物1到0..1人
1到0..1顏色
等等
我嘗試了許多不同的數據注釋和Fluent API組合,但始終會返回相同的錯誤:
“無法檢索Model.Car的元數據”。 無法確定類型'Model.Thing'和'Model.Car'之間的關聯的主要終點。 必須使用關系流利的API或數據注釋顯式配置此關聯的主要端。
我確實通過使用帶有反向注解的virtual並將ID字段設置為Key和ForeignKey來克服了這個錯誤,但是消息跳到Person。 如果您隨后將其設置為與Car相同,則消息將恢復為Car。
看來我可以回過頭來為每個子表創建一個普通的外鍵,但這是很多工作,而且我相信可以通過某種方式使它起作用。 最好使用流暢的API。
如果要使用數據注釋,則還需要將從屬實體的PK聲明為FK:
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Car Car{get;set;}
}
public class Car
{
[Key,ForeignKey("Thing")]
public int ThingId { get; set; }
//other properties
public virtual Thing Thing{get;set;}
}
如果您要使用Fluent Api(從模型中刪除屬性),則配置將如下所示:
modelBuilder.Entity<Car>().HasRequired(c=>c.Thing).WithOptional(t=>t.Thing);
根據指定的多重性,只有Thing
作為主體,而Car
作為從屬才有意義,因為Thing
可以不帶Car
而存在,而Car
必須具有Thing
。
如您所見,您不需要指定ThingId
是此關系的FK,這是因為Entity Framework要求將依賴項的主鍵用作外鍵。 由於沒有選擇,“代碼優先”將為您推斷這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.