Code First EF关系重复

时间:2012-01-26 00:06:54

标签: c# entity-framework ef-code-first entity-relationship

我有一个工作模型,但已注意到该关系已在数据库中创建两次。最初,它在表中创建了两列,但添加了指定的外键属性,现在只有一列。

我有一个帐户类,有许多雇主可以使用该帐户。 (一对多)以下是课程:

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字段的,这是正确的。还有另外两种关系:帐户 - &gt;雇主。 EF已将其命名为Account_EmployersEmployer_Account。这些都是重复的。

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:2)

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; }    
}