在组后选择键

时间:2018-06-01 17:33:14

标签: c# sql entity-framework linq group-by

我尝试在执行分组后选择所有键。如果我将组放入变量然后对变量执行选择,但不直接在组之后执行,则它可以工作。我不知道为什么。

这不起作用:

var pureUsers = from u in userContext.Users
    join ur in userContext.UserRoles on u.UserID equals ur.UserID
    join r in userContext.Roles on ur.RoleID equals r.RoleID
    join sm in userContext.SystemMasters on r.SystemMasterID equals sm.SystemMasterID
    where sm.SystemName == "PURE"
    group ur.UserRoleID by u.SAPID into g
    select g.Key;

它给了我错误,"' string'不包含' Key'的定义没有扩展方法' Key'接受类型' string'的第一个参数。可以找到"

然而,它的工作原理如下:

var pureUsers = from u in userContext.Users
    join ur in userContext.UserRoles on u.UserID equals ur.UserID
    join r in userContext.Roles on ur.RoleID equals r.RoleID
    join sm in userContext.SystemMasters on r.SystemMasterID equals sm.SystemMasterID
    where sm.SystemName == "PURE"
    group ur.UserRoleID by u.SAPID

var happy = pureUsers.Select(x => x.Key);

我也尝试过:

var pureUsers = (from u in userContext.Users
    join ur in userContext.UserRoles on u.UserID equals ur.UserID
    join r in userContext.Roles on ur.RoleID equals r.RoleID
    join sm in userContext.SystemMasters on r.SystemMasterID equals sm.SystemMasterID
    where sm.SystemName == "PURE"
    group ur.UserRoleID by u.SAPID).Select(x => x.Key);

它给了我同样的错误。我不知道这与将它放入pureUsers然后进行选择有什么不同。此外,如果有更好的方法可以做到这一点并不涉及分组,请告诉我。我通过SAPID对其进行分组,因为用户可以拥有许多UserRoles,我想要一个Users.SAPID列表,其中每个SAPID都显示一次。

1 个答案:

答案 0 :(得分:0)

怎么样:

var pureUsers = (from u in userContext.Users
                 join ur in userContext.UserRoles on u.UserID equals ur.UserID
                 join r in userContext.Roles on ur.RoleID equals r.RoleID
                 join sm in userContext.SystemMasters on r.SystemMasterID equals sm.SystemMasterID
                 where sm.SystemName == "PURE"
                 select u.SAPID).Distinct();