简体   繁体   English

EF中多个成员的相同类型之间的自引用关联

[英]Self referencing association between same types in EF for multiple members

I have an employee class inherited from "IdentityUser". 我有一个从“ 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'. 无法确定类型'eHRMS.DAL.Models.Employee'和'eHRMS.DAL.Models.Employee'之间的关联的主要终点。 The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations 必须使用关系流利的API或数据注释显式配置此关联的主体端

Additional Note: I want TeamLead as optional and Manager as Required. 附加说明:我希望TeamLead是可选的,而Manager是必需的。

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). 更新我真正想要的是要有一个雇员列表,每个雇员可以有一个TeamLead(也是雇员类型),并且必须有一个经理(也是雇员类型)。 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: 使用Fluent API,您可以告诉modelbuilder,它是依赖的,并且是可选的:

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: 如果员工需要经理,则可以使用DataAnnotations解决此问题:

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

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

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