2013-06-26 107 views
1

我需要在linq下面寫下sql查詢。我寫了linq查詢這與out子查詢部分。我不知道如何寫在linq編寫LINQ子查詢C#

select * from PART_TYPE Pt 
left join 
(select * from PART_AVAILABILITY where DATE_REF = '2013-06-20')pa 
on Pt.PART_TYPE_ID = pa.PART_TYPE_ID 
where Pt.VEHICLE_ID = 409 

子查詢我怎樣才能做到這一點的想法?

+0

檢查此鏈接以瞭解如何在Linq中編寫子查詢http://stackoverflow.com/questions/418609/how-to-do-subquery-in-linq – Rahul

+0

@Rahul謝謝。我會檢查它。 – Bishan

回答

0
from pt in context.PART_TYPE 
join pa in 
    (
     (from PART_AVAILABILITY in context.PART_AVAILABILITY 
     where 
     PART_AVAILABILITY.DATE_REF == dt 
     select new 
     { 
     PART_AVAILABILITY 
     } 
     ) 
    ) 
on new { PART_TYPE_ID = pt.PART_TYPE_ID } equals new { PART_TYPE_ID = pa.PART_AVAILABILITY.PART_TYPE_ID } into pa_join 
from pa in pa_join.DefaultIfEmpty() 
where 
    pt.VEHICLE == 409 
select new 
{ 
    PART_TYPE = pt, 
    PART_AVAILABILITY = pa.PART_AVAILABILITY            
}; 

dtDateTime對象。

0

這應該是八九不離十:

var query = from pt in part_type 
      join pa in part_availability 
       on new { pt.part_type_id, '2013-06-20' } 
         equals new { pa.part_type_id, pa.date_ref } 
      from x in grp.DefaultIfEmpty() 
      select new { part_type = pt, 
         part_availability = x) }; 

編輯:我突然想起,日期可能是一個問題 - 很容易修復,創造一個DateTime對象和使用,而不是字符串值。

+0

您需要在連接上的第一個匿名類型中指定參數名稱,否則由於內聯字符串而無法編譯。 –

+0

我需要通過'Pt.VEHICLE_ID = 409'和'pa.date_ref'過濾查詢。 – Bishan

0

假設所有表都映射到一個DbContext context

from pt in context.PART_TYPES 
join pa in context.PART_AVAILABILITIES on 
     pt.PART_TYPE_ID equals pa.PART_TYPE_ID 
where pt.VEHICLE_ID == 409 && 
     pa.DATE_REF.Any(r =­> r.DATE_REF == "2013-06-20") 
select new { pt, pa }; 

如果有上PART_TYPE_ID一個FK關係:

from pt in context.PART_TYPES 
where pt.VEHICLE_ID == 409 && pt.PART_AVAILABILITY.DATE_REF == "2013-06-20" 
select pt; 
+0

因'名字'r'在當前上下文中不存在而出錯' – Bishan