我想让所有具有角色的用户按其名称分组,并且还包括没有任何角色的用户。
到目前为止,我正在使用 asp.net 身份 2
from user in users
from identityUserRole in user.Roles
join identityRole in identityRole on identityUserRole.RoleId equals identityRole.Id into r
from roles in r
group roles.Name by user.UserName into g
select new
{
UserName = g.Key,
Roles = g.ToList()
};
但这只返回具有角色的用户。
我更喜欢使用模型来映射数据:
public class UserDto
{
public string UserName { set; get; }
public List<string> Roles { set; get; }
}
然后获取所有用户及其角色名称,如下所示:
var users = (from u in db.Users
let query = (from ur in db.Set<IdentityUserRole>()
where ur.UserId.Equals(u.Id)
join r in db.Roles on ur.RoleId equals r.Id
select r.Name)
select new UserDto { UserName = u.UserName, Roles = query.ToList() })
.ToList();
要使用空角色列表执行"左联接",请尝试:
from roles in r.DefaultIfEmpty()
您还可以将查询简化为此。
var userAndRoles = users.Select(user => new
{
UserName = user.UserName,
Roles = roles.Where(role => user.Roles.Any(userRole => userRole.UserId == user.UserId && userRole.RoleId == role.RoleId))
});