[英]How to tackle complex LINQ queries with outer join?
In my database I have roles and users, I also have user roles to tie the 2 together. 在我的数据库中,我具有角色和用户,我也具有用户角色以将2捆绑在一起。
The problem is trying to get all users with their roles (if they have any, which they may not). 问题是试图让所有用户都拥有他们的角色(如果有,则可能没有)。
I use this query: 我使用以下查询:
return (from ur in db.UserRoles
join r in db.Roles on ur.RoleID equals r.ID
group r by ur.UserProfileID into ugr
join u in db.UserProfiles on ugr.Key equals u.ID
select new UserModel() {
ID = u.ID,
Username = u.UserName,
IsLockedOut = u.IsLockedOut,
LastLoginDate = u.LastLoginDate,
UserRoles = (from r in ugr
select new RoleModel() {
Name = r.Name,
ID = r.ID
}).ToList()
}).ToList();
This works for users who have at least one role, but I also want users who do not have roles. 这适用于至少具有一个角色的用户,但是我也希望没有角色的用户。
I'm currently trying to use http://msdn.microsoft.com/en-us/library/bb397895.aspx DefaultIfEmtpy(), but I don't know how and where to place it, meaning however I try my code does not compile. 我目前正在尝试使用http://msdn.microsoft.com/zh-cn/library/bb397895.aspx DefaultIfEmtpy(),但我不知道如何以及在何处放置它,这意味着我尝试了我的代码不编译。
How do I get all my Users, even if they do not have any UserRoles linked to them? 我如何获得我所有的用户,即使他们没有链接到任何UserRoles?
Get the users first and include their roles from then 首先获取用户,然后再包含他们的角色
return db.UserProfiles
.Include(up => up.UserRoles)
.Select(u => new UserModel() {
ID = u.ID,
Username = u.UserName,
IsLockedOut = u.IsLockedOut,
LastLoginDate = u.LastLoginDate,
UserRoles = u.Roles
.Select(r => new RoleModel() {
Name = r.Name,
ID = r.ID
})
})
.ToList();
return db.UserProfiles
.Include(up => up.UserRoles)
.Include("UserRoles.Roles") // <-- Added further include
.Select(u => new UserModel() {
ID = u.ID,
Username = u.UserName,
IsLockedOut = u.IsLockedOut,
LastLoginDate = u.LastLoginDate,
// Modified this to use joining table
UserRoles = u.UserRoles
.Select(ur => new RoleModel() {
Name = ur.Role.Name,
ID = ur.RoleID
})
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.