Entity Framework Code First Many-To-Many not loading related entities using GUID
I have a self-referencing many-to-many relationship between users and managers that looks like this:
public class User
{
public virtual Guid UserId { get; set; }
public virtual string Username { get; set; }
public virtual ICollection<UsersManagers> Managers { get; set; }
}
public class UsersManagers
{
public int UsersManagersId { get; set; }
public virtual Guid ManagerId { get; set; }
public virtual Guid UserId { get; set; }
public int ManagerRank { get; set; }
[ForeignKey("ManagerId")]
public virtual User Manager { get; set; }
}
So users can have a number of managers that can be sorted by rank. When I seed my database and a user with a few managers, like this:
var user = u.All.Where(e => e.Username == "Neil").FirstOrDefault();
UsersManagers c = new UsersManagers {ManagerRank = 1, ManagerId = manager1.UserId, UserId = user.UserId};
UsersManagers c1 = new UsersManagers { ManagerRank = 2, ManagerId = manager2.UserId, UserId = user.UserId };
Everything is created properly in the database. There are 3 entries in the UsersManagers table with the correct UserId, ManagerId and ManagerRank.
When I load the user from my repository and try to access the Managers property, the collection is empty. What can I do to fix this?
Any help would be appreciated.
Update:
I've added including the Managers when loading Users as suggested below. EF is now returning the wrong mangers for the wrong users. Here is the data from the UsersManagers table, it should be returning 4 managers for 1 user but it is returning 1 manger for 4 of the users.
UsersManagersId ManagerId UserId 开发者_开发百科ManagerRank
1 2157B648-7FE3-4784-A742-687682672EE8 F603EB04-FF22-4E8E-8FB2-3AA12F3F6C8F 1
2 862C2E56-8DF2-4110-B6E4-534B8C0E8F75 F603EB04-FF22-4E8E-8FB2-3AA12F3F6C8F 2
3 A95AD9A2-6475-4B4C-925A-6C0522E9B004 F603EB04-FF22-4E8E-8FB2-3AA12F3F6C8F 3
4 A6D37381-2507-46E8-B84D-059A1B4F1020 F603EB04-FF22-4E8E-8FB2-3AA12F3F6C8F 4
Solution
Solution was to change the ForeignKey annotation for Manager in UsersManagers to use "UserID".
Here is a sample code bit that loads all Sessions and related Trackings for a Program in my repository.
public Program GetById(int id)
{
var entity = _context.Programs
.Include(p => p.Sessions.Select(s => s.Trackings))
.Single(p => p.ID == id);
return entity;
}
精彩评论