简体   繁体   English

实体框架如何在同一张表中设置外键为主键

[英]Entity framework how to set foreign key to primary key in the same table

I am writing with the question how to set foreign key to primary key in the same table.我写的是如何在同一个表中将外键设置为主键的问题。 Code sample (it does not work "may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.")代码示例(它不起作用“可能导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。”)

 class Employee
        {
            [Key]
            public int EmployeeId { get; set; }
            [ForeignKey("EmployeeId")]
            public int ManagerId { get; set; }               
        }

By [ForeignKey("EmployeeId")] , you declare "EmployeeId" as a foreignKey property name which in the first is declared for the primaryKey by [key] annotation.通过[ForeignKey("EmployeeId")] ,您将“EmployeeId”声明为 foreignKey 属性名称,首先通过 [key] 注释为 primaryKey 声明。 You should simply change one of these and add a navigation property of your Manager class or remove all data annotations and let Entity Framework takes care of everything.您应该简单地更改其中之一并添加 Manager class 的导航属性或删除所有数据注释并让 Entity Framework 处理所有事情。

public class Employee
{
   public int EmployeeId { get; set; }

  //Foreign key for Manager
  public int ManagerId { get; set; }
  public Manager Manager { get; set; }
}

public class Manager
{
   public int ManagerId { get; set; }

   public ICollection<Employee> Employees { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM