gpt4 book ai didi

c# - Entity Framework 中的多个自引用关系

转载 作者:太空狗 更新时间:2023-10-29 23:30:09 25 4
gpt4 key购买 nike

我目前有一个名为 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 属性按预期工作。

我该如何解决?

最佳答案

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

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

这是否解决了您的问题?

关于c# - Entity Framework 中的多个自引用关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com