2014-09-26 74 views
2

我想將SQL查詢轉換爲LINQ,但不知道如何使用連接語句中的AND子句,就像我在此示例SQL查詢中所述。如何使用LIN內部LINQ連接

我已經突出顯示了我無法弄清楚的部分。

DECLARE @GroupId INT = 10 

SELECT 
    U.UserName, 
    U.UserID, 
    @GroupId AS "GroupID", 
    CASE WHEN GU.GROUPID IS NULL THEN 0 
     ELSE 1 END 
     AS InGroup 
FROM Users U 
LEFT JOIN GroupUsers GU on GU.UserID = U.UserID 
    AND GU.GROUPID = @GroupId -- HERE!! 

因爲我有

from user in Users 
join gu in GroupUsers on user.UserID equals gu.UserID into subq 
from sub in subq.DefaultIfEmpty() 
where sub.GroupID == 10 || sub == null 
select new 
{ 
    Username = user.UserName, 
    UserId = user.UserID, 
    GroupId = 10, 
    InGroup = sub != null 
} 

,但它使用WHERE刪除數據這是接近。

回答

2

你可以嵌入GroupId條件到查詢:

from user in Users 
join gu in GroupUsers.Where(gu => gu.GroupID == 10) 
    on user.UserID equals gu.UserID into subq 
from sub in subq.DefaultIfEmpty() 
select new 
{ 
    Username = user.UserName, 
    UserId = user.UserID, 
    GroupId = 10, 
    InGroup = sub != null 
} 
+0

謝謝你,這就是我要找的。 – 2014-09-26 13:17:26

0

這是你如何加入多個列:

from user in Users 
join gu in GroupUsers on new { user.UserID, user.GroupID } equals new { gu.UserID, gu.GroupID } subq 
from sub in subq.DefaultIfEmpty() 
select new 
{ 
    Username = user.UserName, 
    UserId = user.UserID, 
    GroupId = sub == null ? null : sub.GroupID, 
    InGroup = sub != null 
}