Search code examples
entity-frameworkrelationshipentities

How to reference a related entity when referenced columns have different names


Suppose I have 3 entities:

public class Department{
   [Key]
   public int DepID {get;set;}
   .......
}
public class Manager{
   [Key]
   public int ManagerID {get;set;}
   .......
}

public class Empoyee{
   [Key]
   public int EmpID {get;set;}
   .......
   public int DepID{get;set}
   public int MngrID{get;set}
}

As you might guess the Employee entity has a relationship with both Department and Manager. Now, if I add this to Employee

 public virtual Department Department { get; set; }

,the entity framework will automatically try to find the department object with DepID in the repository of Departments and assign it to the Employee.Department.(well whenever an Employee is fetched from its repository) This is done easily as both Employee and Department have the joining columns with the same name. But how to enforce the same behavior between Employee and Manager? As you can see the key column in Manager is named ManagerID, whereas the corresponding column in the Employee is MngrID. Is there an attribute for that?


Solution

  • I finally found the proper way of doing this with the help of ForeignKey attribute.

    public class Manager{
       [Key]
       public int ManagerID {get;set;}
       .......
    }
    
    public class Empoyee{
       [Key]
       public int EmpID {get;set;}
       .......
       public int DepID{get;set}
       public int **MngrID**{get;set}
    
       **[ForeignKey("MngrID")]
       public virtual Manager Manager {get;set;}**
    }