[英]Entity Framework added 3 foreign keys for 1 relationship
I have a simple User Class 我有一个简单的用户类
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
}
}
And I also have a Company class defined as 我也有一个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(); } }
}
However, when I run the add-migration
command, it tries to add 3 Foreign keys on the User table to the Company table. 但是,当我运行add-migration
命令时,它尝试将User表上的3个外键添加到Company表中。 Can anyone tell me why this would be the case? 谁能告诉我为什么会这样吗?
AddColumn("dbo.Users", "Company_ID", c => c.Int());
AddColumn("dbo.Users", "Company_ID1", c => c.Int());
AddColumn("dbo.Users", "Company_ID2", c => c.Int());
Entity Framework simply counts the associations between User
and Company
. 实体框架仅计算User
和Company
之间的关联。 It detects three of them: 它检测到其中三个:
Company
in User
. User
Company
。 Employees
in Company
Company
Employees
Managers
in Company
Company
Managers
They're all 1-n
( Company - User
), so, EF concludes, User
needs three foreign keys. 它们都是1-n
( Company - User
),因此,EF得出结论, User
需要三个外键。
You know that Managers
is a computed property. 您知道Managers
是一个计算属性。 In fact, the property shouldn't even be be mapped. 实际上,该属性甚至都不应被映射。 You should add the [NotMapped]
attribute to it or map it as ignored by the fluent mapping API. 您应该向其添加[NotMapped]
属性,或者将其映射为流畅的映射API所忽略的属性。
Also, you know that User.Company
and Company.Employees
are two ends of one association. 另外, 您知道User.Company
和Company.Employees
是一个关联的两端。 But because of the two ICollection<User>
properties, EF doesn't know which one to choose for the other end (the inverse end ) of User.Company
. 但是由于有两个ICollection<User>
属性,EF不知道为User.Company
的另一端( 反向端 )选择User.Company
。
Now if you unmap Company.Managers
, EF will see two properties -- User.Company
and Company.Employees
-- and assume they belong together. 现在,如果取消映射Company.Managers
,EF将看到两个属性User.Company
和Company.Employees
并假定它们属于User.Company
属性。 So by unmapping one property, only one foreign key will be created. 因此,通过取消映射一个属性,将仅创建一个外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.