[英]Entity Framework Core 5.0 - Many to many with additional field in mapping table
[英]Entity Framework join table with additional field
關於實體框架的最佳實踐問題。
我有一個Cases表和一個Users表,我想加入他們的多對多關系。 但是,我希望連接本身能夠將關於該關系的信息存儲在“UserType”字段中。
在SQL中很容易做 - 兩個主數據表和第三個用外鍵鏈接兩個數據表,並包含一個額外的UserType列。
create table #user ( UserId int, Info nvarchar(4000) )
create table #case ( CaseId int, Info nvarchar(4000) )
create table #jointable ( UserId int, CaseId int, UserType nvarchar(99))
令我困惑的是EF能夠自己定義連接表,將其從開發人員手中奪走。 在這個例子中,我是否需要將所有三個定義為EF類,或者是否有一種方法可以構建它,我只定義了兩個類,Case和User,讓EF為我處理連接,同時仍然獲取我的UserType?
我正在使用“代碼優先”EF,而不是那應該對解決方案有很大影響。
干杯,馬特
EF負責僅使用簡單的多對多關系創建連接表。 與您的情況一樣,我沒有看到任何其他方式,但顯式創建連接類
public class UserCase
{
public virtual User User { get; set; }
public virtual Case Case { get; set; }
public virtual string UserType { get; set; }
}
使用EF實現此目的的唯一方法是創建兩個one-to-many
關系:
public class User
{
public int UserId {get; set;}
public string Info {get; set;}
public virtual ICollection<UserCase> UserCase {get; set;}
}
public class Case
{
public int CaseId {get; set;}
public string Info {get; set;}
public virtual ICollection<UserCase> UserCase {get; set;}
}
public class UserCase
{
public int CaseId {get; set;}
public int UserId {get; set;}
public virtual Case Case {get; set;}
public virtual User User {get; set;}
public string UserType {get; set;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.