2013-06-26 104 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