2010-10-20 71 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