我需要在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
我该怎么做?
这应该非常接近:
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
对象并使用它而不是字符串值的问题。
假设所有表都映射到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;
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
是DateTime
对象。