简体   繁体   中英

Self referencing association between same types in EF for multiple members

I have an employee class inherited from "IdentityUser".

  public class Employee : IdentityUser
    { 
       public String Name { get; set; }
       public string ManagerID { get; set; }
       public virtual Employee Manager { get; set; }
    } 

This works fine, but when I add another property of same type, like

public virtual Employee TeamLead { get; set; }

It throws the following exception:

Unable to determine the principal end of an association between the types 'eHRMS.DAL.Models.Employee' and 'eHRMS.DAL.Models.Employee'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations

Additional Note: I want TeamLead as optional and Manager as Required.

UPDATE What i really want is to have a list of employees, each employee can have a TeamLead(which is also an Employee type) and must have a Manager (also Employee Type). Manager is required, means there will be atleast one employee who is manager of itself.

The error message tells you, that it does not know, which entity is dependent on which.

Using the Fluent API you could tell the modelbuilder, which is dependet and which is optional with this:

modelBuilder.Entity<Employee>()
            .HasOptional(f => f.TeamLead)
            .WithRequired(s => s.Manager);

If the manager is required for an employee, you could use DataAnnotations to solve this one:

public class Employee : IdentityUser
{ 
   public String Name { get; set; }
   public string ManagerID { get; set; }

   [Required]
   public virtual Employee Manager { get; set; }

   public virtual Employee TeamLead { get; set; }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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