2009-07-01 197 views
2

我可以在LINQ to SQL上進行這種類型的SQL查詢嗎?如何使用from語句中的子查詢進行LINQ查詢?

(這個查詢僅僅是一個例子)

select * 
from orders as o 
left outer join (select * from ordersdetail where status = 'A') as od 
on o.id = od.orderid 

我需要的是我怎麼能放到裏面去一個子查詢「從」語句。

感謝

回答

4

只要做到以通常的方式訂購內容的條件:

from o in orders 
join od from orderdetails on o.id = od.orderid 
    into details 
where details.status == 'A' 
select new { Order = o, Details = details} 

(NB細節是一個序列,每個匹配細節記錄,LINQ運營商如第一和FirstOrDefault可以使用。以提取只是一個。)

或者使用表達式作爲數據源

from o in orders 
join od from orderdetails.Where(d => d.Status == 'A') on o.id = od.orderid 
    into details 
select new { Order = o, Details = details} 

甚至,使用另一種理解表達作爲源表達:(設置你DataContextLog屬性,可以看到SQL,所以你可以比較一下什麼是真正生成的SQL)

from o in orders 
join od from (from d in orderdetails 
       where d.Status == 'A' 
       select d) 
    on o.id = od.orderid 
    into details 
select new { Order = o, Details = details} 

編輯:更改爲使用組加入(... into var)以獲取外部聯接(而不是內部聯接)。

+0

+1三個備選方案 – Andomar 2009-07-01 16:59:08

0

你可以用試試這個功能在哪裏:

from o in orders 
join od in ordersdetail.Where(x => x.status == 'A') on o.id = od.orderid 
select new { Order = o, Details = od} 
相關問題