如何在Linq查询上获取外部联接

时间:2010-10-20 13:36:42

标签: linq linq-to-entities

鉴于此linq查询

from c in context.Customers
from o in c.Orders
where c.City == "MyCity" || o.ShipTo == "MyCity"
select c

如果客户的城市是“MyCity”但没有任何订单,则查询不会返回任何行。这是因为客户和订单之间存在隐含的内部联接。如何选择城市为“MyCity”或订单发货到“MyCity

的客户

在这种情况下,我需要在客户和订单之间进行外部联接。我如何在Linq中表达这一点?我认为大致的TSQL是

select customers.* 
from customers 
left join orders on customers.id = orders.customerid
where customers.city = 'MyCity' or orders.ShipTo = 'MyCity'

2 个答案:

答案 0 :(得分:1)

要获得外部联接,可以使用DefaultIfEmpty。请参阅此问题:Linq to Sql: Multiple left outer joins

from c in context.Customers
from o in context.Orders
    .Where(a => a.customerid == c.id)
    .DefaultIfEmpty()
where c.City == "MyCity" || o.ShipTo == "MyCity"
select c

或者,你可以这样做:

from c in context.Customers
join o in context.Orders on c.id equals o.customerid into g
from x in g.DefaultIfEmpty() 
where c.City == "MyCity" || x.ShipTo == "MyCity"
select c

我相信他们都会生成相同的SQL。

答案 1 :(得分:0)

您必须使用DefaultIfEmpty

我觉得这样的事情会起作用

var result = from c in context.Customers
    join o in c.Orders on c.CustomerId equals o.CustomerId into lj
    from or in lj.DefaultIfEmpty()
    where c.City == "MyCity" || or.ShipTo == "MyCity"
    select c