Linq to Sql的子查询

时间:2011-03-26 04:31:55

标签: linq-to-sql

我遵循LINQ声明。如何更改此设置,以便仅在子查询中获取GroupID。 我的语法不起作用。

并且只有不同的用户。

from u in Users 
join ug in UserGroups on u.UserID equals ug.UserID
where ug.GroupID == (from igr in UserGroups where igr.UserID == 1 select igr.GroupID)
select u

3 个答案:

答案 0 :(得分:1)

为了便于阅读,我会把它分成两个单独的查询,但这里是

var group = from igr in UserGroup
            where irg.UserID == 1
            select igr.GroupID;

var result = from u in Users 
              join ug in UserGroups on u.UserID equals ug.UersID
              into x
              where group.Contains( x.GroupID )
              select x;

作为一个查询我相信它会像这样工作

var result = from u in Users 
              join ug in UserGroups on u.UserID equals ug.UersID
              into x
              where 
                (from igr in UserGroup
                 where irg.UserID == 1
                 select igr.GroupID).Contains( x.GroupID )
              select x;

答案 1 :(得分:1)

这就是当时的结果。

var query = (from u in _dbctx.Users
    join ug in _dbctx.UserGroups on u.UserID equals ug.UserID
    where _dbctx.UserGroups.Any(igr => igr.GroupID == ug.GroupID && igr.UserID == 1)
    select GetUser(u)).Distinct();

答案 2 :(得分:0)

    from u in Users 
    join ug in UserGroups on u.UserID equals ug.UserID
    where ug.GroupID == (from igr in UserGroups where igr.UserID == 1 select  igr.GroupID).FirstOrDefault()
    select u

内部查询必须返回一个值