开发者

Entity Framework Code First Self-Referencing Many-to-Many with additional properties using wrong Id

I'm trying to model a self-referencing Many-to-Many relationship between Employees and Managers using EF code first (where manag开发者_开发百科ers are employees). On top of keeping track of which managers an Employee has I need to store a managers rank. I'm assuming I'll need to create a linking class so that I can store the rank.

My POCO classes look something like this:

public class Employee
{
public Guid EmployeeId {get; set;}
public String Name {get; set;}
public virtual ICollection<EmployeeManagers> EmployeeManagers { get; set; }
}

public class EmployeeManager
{
public int EmployeeManagerId {get; set;}
public int Rank {get; set;}
public Guid EmployeeId {get; set;}
public Guid ManagerId {get; set;}
public virtual Employee Manager {get; set;}
}

It seems to work fine except when I use the Manager object in the EmployeeManager class. It is using the EmployeeId to load the Manager object instead of the ManagerId. So if an employee has 4 managers, it loads the Employee into the Manager object instead of the 4 managers.

Have I modelled this correctly and is there a way to force EF to use the ManagerId to load the Manager?

EDIT:

Anyone have any idea why the entity framework would use the EmployeeId to try load the Manager? The order that the properties appear in doesn't make any difference and surely ManagerId is a more likely foreign key for loading a Manager than EmployeeId?


Fixed this by adding the ForeignKey attribute:

    [ForeignKey("ManagerId")]
    public virtual Employee Manager { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜