简体   繁体   English

编写LINQ子查询C#

[英]Write LINQ subquery C#

I need to write below sql query in linq . 我需要在linq编写下面的sql查询。 i wrote linq query for this with out sub query part. 我为此写了linq查询,没有子查询部分。 i have no idea about how to write sub query in 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

How can i do this ? 我怎样才能做到这一点 ?

This should be pretty close: 这应该非常接近:

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) };

EDIT: It occurs to me, the date might be an issue -- easy enough to fix that creating a DateTime object and using that instead of the string value. 编辑:对我来说,日期可能是个问题-足够容易地修复创建DateTime对象并使用它而不是字符串值的问题。

Assuming all tables are map to a DbContext context 假设所有表都映射到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 };

If there is a FK relationship on PART_TYPE_ID : 如果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;
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                                            
};

dt is DateTime object. dtDateTime对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM