如何使用LINQ展平表

时间:2017-07-25 20:22:15

标签: c# linq

我有这个问题:

var usersByBranch = (from u in _db.VRT_User
                             join urb in _db.VRT_UserRoleBranch on u.UserId equals urb.UserId
                             join r in _db.VRT_Role on urb.RoleId equals r.RoleId
                             where branches.Contains(urb.BranchId)
                             select new UserRoleBranchModel
                             {
                                 UserId = u.UserId,
                                 BranchId = urb.BranchId,
                                 RoleId = urb.RoleId,
                                 RoleName = r.RoleName
                             });

在此查询中,对于同一个userId,将单独返回具有相同BranchId的roleId(1-4)和RoleName。

我希望展平行,以便具有相同userId的行包含同一BranchId中的所有RoleId和RoleName。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

var usersByBranch = (from u in _db.VRT_User
                             join urb in _db.VRT_UserRoleBranch on u.UserId equals urb.UserId
                             join r in _db.VRT_Role on urb.RoleId equals r.RoleId
                             where branches.Contains(urb.BranchId)
group u by u.UserId into g
                             select new UserRoleBranchModel
                             {
                                 UserId = g.Key,
                                 BranchId = g.First().BranchId,
                                 RoleId = g.First().RoleId,
                                 RoleName = g.First()RoleName
                             });

答案 1 :(得分:1)

不确定包含的含义,但是您不能使用相同的UserRoleBranchModel来保存多个角色,因此匿名对象可以完成这项任务:

var usersByBranch = (from u in _db.VRT_User
                     join urb in _db.VRT_UserRoleBranch on u.UserId equals urb.UserId
                     join r in _db.VRT_Role on urb.RoleId equals r.RoleId
                     where branches.Contains(urb.BranchId)
                     group r by new { urb.UserId, urb.BranchId } into rg
                     select new {
                         UserId = rg.Key.UserId,
                         BranchId = rg.Key.BranchId,
                         Roles = rg.Select(r => r)
                     });