【问题标题】:Write LINQ subquery C#编写 LINQ 子查询 C#
【发布时间】:2013-06-23 01:23:25
【问题描述】:

我需要在linq 中写下面的sql 查询。我为此写了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

我该怎么做?

【问题讨论】:

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


【解决方案1】:
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 对象。

【讨论】:

    【解决方案2】:

    假设所有表都映射到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;
    

    【讨论】:

    • 收到错误The name 'r' does not exist in the current context
    【解决方案3】:

    这应该非常接近:

    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 对象并使用它而不是字符串值的问题。

    【讨论】:

    • 你需要在join的第一个匿名类型中指定参数名称,否则由于内联字符串而无法编译。
    • 我需要通过Pt.VEHICLE_ID = 409pa.date_ref 过滤查询。
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多