我试图将SQL查询转换为linq,但不知道如何在连接语句中使用AND子句,就像我在此示例SQL Query中一样。
我已经突出了我在下面无法弄清楚的部分。
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
会删除数据。
答案 0 :(得分: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
}
答案 1 :(得分: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
}