Code First EF关系重复
本文关键字:关系 EF First Code | 更新日期: 2023-09-27 18:21:31
我有一个工作模型,但注意到该关系已经在数据库中创建了两次。最初,它在表中创建了两列,但添加了指定的外键属性后,现在只有一列。
我有一个账户类,有很多雇主可以使用该账户。(一对多)以下是类别:
public class Account
{
public int AccountId { get; set; }
[Required(ErrorMessage = Constants.ValidationMessages.FieldRequired)]
public string Name { get; set; }
public int? PrimaryUserId { get; set; }
[ForeignKey("PrimaryUserId")]
public Employer PrimaryUser { get; set; }
[ForeignKey("EmpAccountId")]
public ICollection<Employer> Employers { get; set; }
}
这是继承的雇主级
public class Employer : User
{
public Employer()
{
DepartmentsToPost = new Collection<Department>();
Contacts = new Collection<Contact>();
}
[Display(Name = "Workplaces to advertise jobs")]
public virtual ICollection<Department> DepartmentsToPost { get; set; }
public int EmpAccountId { get; set; }
[ForeignKey("EmpAccountId")]
public virtual Account Account { get; set; }
public override string UserType
{
get { return "Employer"; }
}
}
用户表:
UserId
Username
FirstName
Surname
EmpAccountId
Discriminator
账户表
AccountId
Name
PrimaryUserId
有一个返回User表的链接,这是针对PrimaryUser
字段的,这是正确的。还有另外两种关系:客户->雇主。EF将它们命名为CCD_ 2和CCD_。这些是重复的。
如何防止这种情况发生?
Employers
集合应使用InversePropertyAttribute进行装饰,以指向另一侧的导航属性。
public class Account
{
public int AccountId { get; set; }
[Required(ErrorMessage = Constants.ValidationMessages.FieldRequired)]
public string Name { get; set; }
public int? PrimaryUserId { get; set; }
[ForeignKey("PrimaryUserId")]
public Employer PrimaryUser { get; set; }
[InverseProperty("Account")]
public ICollection<Employer> Employers { get; set; }
}