实体框架中的多个自引用关系

时间:2015-09-17 11:13:34

标签: c# .net asp.net-mvc entity-framework

我目前有一个名为EmployeeDetails的课程,如下所示。

public class EmployeeDetails {

    public int EmployeeDetailsId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }

    [ForeignKey("Manager")]
    public int? ManagerId { get; set; }
    public virtual EmployeeDetails Manager { get; set; }
    [ForeignKey("LineManager")]
    public int? LineManagerId { get; set; }
    public virtual EmployeeDetails LineManager { get; set; }

}

我尝试添加ManagerLineManager属性,这些属性将引用相同类型的对象。 当我尝试添加迁移时,我收到以下错误:

无法确定类型EmployeeDetailsEmployeeDetails之间关联的主要结尾。

在添加ManagerId,LineManagerId和LineManager属性之前,Manager属性按预期工作。

我该如何解决?

1 个答案:

答案 0 :(得分:3)

您必须指定关系的另一面。像这样:

public class EmployeeDetails
{

    public int EmployeeDetailsId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }

    [ForeignKey("Manager")]
    public int? ManagerId { get; set; }

    public virtual EmployeeDetails Manager { get; set; }

    [ForeignKey("LineManager")]
    public int? LineManagerId { get; set; }

    public virtual EmployeeDetails LineManager { get; set; }

    [ForeignKey("ManagerId")]
    public virtual ICollection<EmployeeDetails> ManagedEmployees { get; set; }

    [ForeignKey("LineManagerId")]
    public virtual ICollection<EmployeeDetails> LineManagedEmployees { get; set; }

}

生成的迁移

CreateTable(
    "dbo.EmployeeDetails",
    c => new
        {
            EmployeeDetailsId = c.Int(nullable: false, identity: true),
            Name = c.String(),
            Title = c.String(),
            ManagerId = c.Int(),
            LineManagerId = c.Int(),
        })
    .PrimaryKey(t => t.EmployeeDetailsId)
    .ForeignKey("dbo.EmployeeDetails", t => t.LineManagerId)
    .ForeignKey("dbo.EmployeeDetails", t => t.ManagerId)
    .Index(t => t.ManagerId)
    .Index(t => t.LineManagerId);

这能解决您的问题吗?