在实体框架的多个自引用关系 [英] Multiple self-referencing relationships in Entity Framework

查看:100
本文介绍了在实体框架的多个自引用关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个名为 EmployeeDetails 类,它看起来像下面。

I currently have a class called EmployeeDetails which looks like below.

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

}

我想补充,这将参考同一个类型的对象管理​​ LineManager 属性。
当我尝试并添加迁移我收到以下错误:

I'm trying to add Manager and LineManager properties which will reference objects of the same type. When I try and add a migration I get the following error:

无法确定类型之间的关联的主要结束<$​​ C $ C> EmployeeDetails 和 EmployeeDetails

Unable to determine the principal end of an association between the types EmployeeDetails and EmployeeDetails.

manager属性和预期一样添加经理ID, LineManagerId 和LineManager属性之前。

The Manager property worked as expected before adding the ManagerId, LineManagerId and LineManager properties.

我该如何解决呢?

推荐答案

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

You have to specify the other side of the relationship. Like this:

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

这是否解决问题了吗?

Does that solve your problem?

这篇关于在实体框架的多个自引用关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆