2010-10-20 78 views
0

鉴于这种LINQ查询如何获得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' 

回答

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

是它们产生相同的SQL。我喜欢第二种选择的样子。谢谢。 – 2010-10-20 14:51:11

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