2011-03-26 197 views
0

我有以下的LINQ語句。我如何改變這個,所以我只在子查詢中得到GroupID。 我的語法在這裏不起作用。Linq to Sql的子查詢

而且也只有不同的用戶。

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 

回答

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

這是怎麼做的然後結束。

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(); 
+0

StackOverflow的使用降價的格式(見:http://daringfireball.net/projects/markdown/syntax)。像'[code] [/ code]'這樣的東西在這裏不起作用。 – 2012-03-07 17:30:00

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 

內查詢必須恰好返回一個值