我有一个非常基本的SQL连接语句,我似乎无法弄清楚如何使它在LINQ中工作。它在JOIN中使用OR语句,我在网上找到了在JOIN中使用AND的代码,但在我的情况下对OR没有任何帮助。
这是SQL:
SELECT *
FROM Proposals AS a
LEFT JOIN Proposal_Minions AS b
ON a.ID = b.Proposal_ID
LEFT JOIN Users AS c
ON (a.PI_User_ID = c.ID) OR (a.Creator_User_ID = c.ID) OR (b.User_ID = c.ID)
WHERE c.Account = 'myname'
非常感谢任何帮助。
答案 0 :(得分:1)
您可以使用where
代替join
:
from a in Proposals
join b in Proposal_Minions on a.ID equals b.Proposal_ID
from c in Users
where a.PI_User_ID == c.ID || a.Creator_User_ID == c.ID || b.User_ID == c.ID
select new { a, b, c }
但是,这相当于INNER JOIN
。您可以通过
from a in Proposals
join b in Proposal_Minions on a.ID equals b.Proposal_ID into j
from pm in j.DefaultIfEmpty()
select new { a,
pm,
c = (from c in Users
where a.PI_User_ID == c.ID
|| a.Creator_User_ID == c.ID
|| pm.User_ID == c.ID
select c).FirstOrDefault()
}
如果您只想选择Proposal
,
from a in Proposals
join b in Proposal_Minions on a.ID equals b.Proposal_ID into j
from pm in j.DefaultIfEmpty()
where Users.Any(u => a.PI_User_ID == u.ID
|| a.Creator_User_ID == u.ID
|| pm.User_ID == u.ID)
select a
但这不再是Users
上的外部联接。另一方面,Users
和Proposal_Minions
上的外部联接会破坏其过滤目的,因为无论如何都将选择所有Proposals
。 Proposal_Minions
上的外部联接仍然如此。
答案 1 :(得分:1)
如果需要,您可以针对数据库上下文执行原始sql,并将结果映射到强类型(确保查询结果与类型匹配),例如。
IEnumerable<YourStronglyTypedTable> myResults =
dbConext.ExecuteQuery<YourStronglyTypedTable>("Your SELECT query");