Linq:多个子连接或子查询

时间:2010-11-06 21:18:10

标签: linq-to-sql asp.net-membership subquery left-join membership-provider

我很确定我可以从单个Linq语句中获得我想要的结果,我自己无法找到它!这就是我到目前为止所做的:

var query = from uir in Aspnet_UsersInRoles
        join r in Aspnet_Roles
        on uir.RoleId equals r.RoleId 
        select new
        {
            UserId = uir.UserId,
            RoleName = r.RoleName
        };

var query2 = from q in query
        group q by q.UserId into roles
        select new 
        {
            UserId = roles.Key,
            Roles = roles.Distinct()
        };

var query3 = from u in Aspnet_Users
        join q in query2
        on u.UserId equals q.UserId
        select new
        {
            UserId = u.UserId,
            UserName = u.UserName,
            Roles = q.Roles
        };

预期结果: Expected Results

,这甚至都不正确:我真的不需要在'角色'列表/ IEnumerable中有UserId,只需要每个UserId的RoleName列表。

我正在使用asp.net成员资格sql表,基本上我想得到一个用户列表,包括他们的角色。

  • 每个用户可能有多个角色。
  • 用户可能根本没有角色(并且仍应显示结果)

您能否帮助我或指导我如何从单一的Linq声明中获得相同的结果?

PS。是的,我是Linq新手和SQL老手,这可能会掩盖我的想法。

修改

好的,我想我正在接受它:

var q = from u in Aspnet_Users
    from up in UserProfiles.Where( _up => _up.UserId == u.UserId ).DefaultIfEmpty()
    from uir in Aspnet_UsersInRoles.Where( _uir => _uir.UserId == u.UserId ).DefaultIfEmpty()
    from r in Aspnet_Roles.Where( _r => _r.RoleId == uir.RoleId).DefaultIfEmpty()
    group r.RoleName by new     {
                                u.UserId, 
                                u.UserName, 
                                up.FirstName, 
                                up.LastName, 
                                u.LastActivityDate
                                } into g
    select new 
    {
        userID = g.Key.UserId,
        firstName = g.Key.FirstName,
        lastName = g.Key.LastName,
        userName = g.Key.UserName,          
        lastActivityDate = g.Key.LastActivityDate,
        roles = g.Distinct()
    };
你怎么看? (我从我自己的UserProfiles表中添加了信息,与Aspnet_Users的关系为1:1)

1 个答案:

答案 0 :(得分:1)

我相信这是等价的。

var query = from userRole in Aspnet_UsersInRoles
            join role in Aspnet_Roles on userRole.RoleId equals role.RoleId 
            group role.RoleName by userRole.UserId into roles
            join user in Aspnet_Users on roles.Key equals user.UserId
            select new
            {
                user.UserId,
                user.UserName,
                Roles = roles.Distinct(),
            };

看看这是否成功。