[英]Entity Framework added 3 foreign keys for 1 relationship
我有一個簡單的用戶類
public class User
{
public int ID { get; set; }
[Required]
public virtual ApplicationUser LoginID { get; set; }
[Required]
public string Name { get; set; }
public string JobTitle { get; set; }
[DefaultValue(UserRole.Standard)]
public UserRole Role { get; set; }
public virtual Company Company { get; set; }
public string Email { get { return LoginID.Email; } }
public bool HasAccess(UserRole TargetRole)
{
//Non-relevant logic
}
}
我也有一個Company類定義為
public class Company
{
public int ID { get; set; }
[Required]
[MaxLength(length: 70)]
public string Name { get; set; }
public virtual ICollection<User> Employees { get; set; }
public virtual ICollection<CompanyEmailDomain> Domains { get; set; }
public ICollection<User> Managers { get { return Employees.Where(x => x.Role == UserRole.Manager).ToList(); } }
}
但是,當我運行add-migration
命令時,它嘗試將User表上的3個外鍵添加到Company表中。 誰能告訴我為什么會這樣嗎?
AddColumn("dbo.Users", "Company_ID", c => c.Int());
AddColumn("dbo.Users", "Company_ID1", c => c.Int());
AddColumn("dbo.Users", "Company_ID2", c => c.Int());
實體框架僅計算User
和Company
之間的關聯。 它檢測到其中三個:
User
Company
。 Company
Employees
Company
Managers
它們都是1-n
( Company - User
),因此,EF得出結論, User
需要三個外鍵。
您知道Managers
是一個計算屬性。 實際上,該屬性甚至都不應被映射。 您應該向其添加[NotMapped]
屬性,或者將其映射為流暢的映射API所忽略的屬性。
另外, 您知道User.Company
和Company.Employees
是一個關聯的兩端。 但是由於有兩個ICollection<User>
屬性,EF不知道為User.Company
的另一端( 反向端 )選擇User.Company
。
現在,如果取消映射Company.Managers
,EF將看到兩個屬性User.Company
和Company.Employees
並假定它們屬於User.Company
屬性。 因此,通過取消映射一個屬性,將僅創建一個外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.