实体框架,将2 X 1对1关系映射到同一模型

时间:2018-10-31 08:50:22

标签: c# entity-framework linq

我有2个实体框架模型,第一个是Employee模型,第二个是Lead模型。每个新产生的潜在客户有2名员工。第一个进行冷打,第二个进行跟进。 Employee模型的主键是EmployeeId和Lead模型,我想像EmployeeId1和EmplyeeId2一样有两个外键,它们都与Employee模型建立1对1的关系

public class Lead
{
   [Key]
   public int LeadId { get; set; }

   public string FirstName { get; set; }

   public string LastName { get; set; }

   //foreign key to EmployeeId in Employee model
   public int EmplyeeId2 { get; set; }

   //second foreign Key to EmployeeId in Employee model
   public int EmplyeeId1 { get; set; }

   public virtual Employee Employee {get; set;}
}

关于最佳方法的任何想法,这样我就可以使用Lead.Employee.EmployeeName之类的东西访问Linq中的链接属性?

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题:)

public class Lead {
    [Key]
    public int LeadId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    //foreign key to EmployeeId in Employee model
    public int EmplyeeId2 { get; set; }

    //second foreign Key to EmployeeId in Employee model
    public int EmplyeeId1 { get; set; }

    [ForeignKey("EmplyeeId1")]
    public virtual Employee Employee1 {get; set;}

    [ForeignKey("EmplyeeId2")]
    public virtual Employee Employee2 {get; set;}
}

答案 1 :(得分:0)

当您有一个Employee类和两个从该类继承的类时,可以创建一个方案。但是,我认为将此类命名为Employee1和Employee2并不是一个好主意,它们的名称可能与此员工的某些特征(例如经理和主管)相关。

班级员工

public class Employee 
{
 public string FName {get; set;}
 public string LName{ get; set;}
 // other properties
 }

班长:

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

 public int LeadId{ get; set;}
 public virtual Lead Lead{ get; set;}
 // other properties
 }

班主任:

public class Supervisor: Employee 
{
 public int SupervisorId {get; set;}
 public virtual Lead Lead{ get; set;}
 public int LeadId{ get; set;}
 // other properties
 }

班长:

 public class Lead
{
   [Key]
   public int LeadId { get; set; }

   public string FirstName { get; set; }

   public string LastName { get; set; }

   //foreign key to EmployeeId in Employee model
   public int SupervisorId { get; set; }

   //second foreign Key to EmployeeId in Employee model
   public int ManagerId { get; set; }

   public virtual Manager Manager{ get; set;} 
   public virtual Supervisor Supervisor {get; set;}
}

使用流畅的api的Foregn Key:

modelBuilder.Entity<Lead>()
            .HasOne(p => p.Manager)
            .WithOne(i => i.Lead)
            .HasForeignKey<Manager>(b => new {b.ManagerId, b.SupervisorId}); 
相关问题