编写LINQ子查询C#

时间:2013-06-26 03:24:49

标签: c# sql linq subquery sql-to-linq-conversion

我需要在linq中编写下面的sql查询。我用out子查询部分写了linq查询。我不知道如何在linq

中编写子查询
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

我该怎么做?

3 个答案:

答案 0 :(得分: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对象并使用它而不是字符串值。

答案 1 :(得分: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;

答案 2 :(得分: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对象。