Pergunta

I've got a pretty basic SQL join statement that I can't seem to figure out how to make it work in LINQ. It is using OR statements in a JOIN and I have found code online for using ANDs in a JOIN but nothing helpful for ORs in my situation.

Here is the 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'

Any help would be greatly appreciated.

Foi útil?

Solução

You can use where in stead of 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 }

However, this would be the equivalent of INNER JOIN. You can get an outer join effect by

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

As you want to select the Proposals only you could do

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

but this is not an outer join on Users any more. On the other hand, an outer join on both Users and Proposal_Minions would defeat their filter purpose as all Proposals will be selected anyway. This is still true for the outer join on Proposal_Minions.

Outras dicas

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");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top