2009-04-15 87 views
12

我對Linq To SQL相當新,但試圖運行一個相當簡單的SQL查詢,並且無法弄清楚如何使它在LINQ中表現良好。Linq To SQL並有

SELECT  Users.Id, Users.Id AS Expr1, Users.FirstName, Users.LastName, 
User_x_Territory.UserID 
FROM   Users LEFT OUTER JOIN 
      User_x_Territory ON User_x_Territory.UserID = Users.Id 
GROUP BY Users.Id, Users.Id, Users.FirstName, Users.LastName, User_x_Territory.UserID 
HAVING  (COUNT(User_x_Territory.UserID) = 0) 

只是試圖讓沒有領土分配,告訴他們是否有領土是檢查user_x_territory gerrund的唯一途徑的所有用戶。

我能夠用它來獲取所有用戶的我的DB的:

var users = from u in db.Users 
      join uXt in db.User_x_Territories on u equals uXt.User into gerr 
      from users in gerr.DefaultIfEmpty() 
      select users; 

但是從那裏我無法弄清楚如何/有細化搜索結果添加組只顯示沒有地區的用戶。

感謝您的任何幫助。

回答

13

我建議以下解決方案。

db.Users.Where(u => u.User_x_Territories.Count == 0) 
+0

真棒!謝謝你,我不知道你能做到這一點使用LINQ。 – Chelsea 2009-04-15 20:43:15

1

我不知道如何有效的,這是(我猜不是很),但你可以嘗試這樣的事:

var users = (from u in db.Users 
      join uXt in db.User_x_Territories on u equals uXt.User into gerr 
      from users in gerr.DefaultIfEmpty() 
      select u).Where(u => u.User_x_Territories.Count == 0); 
1

編輯:嘿,你猜有人打我給它:(

 
from t in db.Users 
join t0 in db.User_x_Territory on new { UserID = t.Id } equals new { UserID = t0.UserID } into t0_join 
from t0 in t0_join.DefaultIfEmpty() 
group new {t, t0} by new { 
    t.Id, 
    Column1 = t.Id, 
    t.FirstName, 
    t.LastName, 
    t0.UserID 
} into g 
where g.Count() == 0 
select new { 
    Id = g.Key.Id, 
    Expr1 = g.Key.Id, 
    g.Key.FirstName, 
    g.Key.LastName, 
    UserID = g.Key.UserID 
}