0

我有一个非常基本的 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'

任何帮助将不胜感激。

4

2 回答 2

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()
            }

因为你想选择Proposals 只有你可以做

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。另一方面,两者的外部连接UsersProposal_Minions破坏它们的过滤器目的,因为Proposals无论如何都会被选中。对于外部连接,这仍然适用Proposal_Minions

于 2013-08-21T18:55:02.810 回答
1

You can execute raw sql against your DB context if needed, and map results to strong type (make sure query result matches the type) e.g.

IEnumerable<YourStronglyTypedTable> myResults = 
dbConext.ExecuteQuery<YourStronglyTypedTable>("Your SELECT query");
于 2013-08-21T18:57:33.500 回答