[英]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.
UsersManagers 表中有 3 个条目具有正确的 UserId、ManagerId 和 ManagerRank。
When I load the user from my repository and try to access the Managers property, the collection is empty.当我从存储库加载用户并尝试访问Managers属性时,该集合为空。 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.
EF 现在为错误的用户返回错误的管理器。 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.
这是来自 UsersManagers 表的数据,它应该为 1 个用户返回 4 个经理,但它为 4 个用户返回 1 个经理。
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".解决方案是更改 UsersManagers 中 Manager 的 ForeignKey 注释以使用“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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.