Multiple self-regulation relationships in the Entity Framework

I currently have a class called EmployeeDetails that looks 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; } } 

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

It is not possible to determine the main end of the association between types EmployeeDetails and EmployeeDetails .

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

How can I solve it?

+5
source share
1 answer

You must indicate 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; } } 

Generated migration

 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 your problem solve?

+3
source

All Articles