我可以在LINQ to SQL上进行这种类型的SQL查询吗?
(此查询只是一个例子)
select *
from orders as o
left outer join (select * from ordersdetail where status = 'A') as od
on o.id = od.orderid
我需要的是如何将子查询放在de“from”语句中。
由于
答案 0 :(得分:4)
以通常的方式执行订单详细信息:
from o in orders
join od from orderdetails on o.id = od.orderid
into details
where details.status == 'A'
select new { Order = o, Details = details}
(注意。详细信息是一个序列,每个匹配的详细信息记录,像First和FirstOrDefault这样的LINQ运算符只能用于提取一个。)
或使用表达式作为数据源
from o in orders
join od from orderdetails.Where(d => d.Status == 'A') on o.id = od.orderid
into details
select new { Order = o, Details = details}
甚至,使用另一个理解表达式作为源表达式:
from o in orders
join od from (from d in orderdetails
where d.Status == 'A'
select d)
on o.id = od.orderid
into details
select new { Order = o, Details = details}
(设置DataContext
的{{1}}属性允许您查看SQL,以便比较实际生成的SQL。)
编辑:更改为使用群组加入(Log
)来获取外部联接(而不是内部联接)。
答案 1 :(得分:0)
您可以使用Where函数尝试此操作:
from o in orders
join od in ordersdetail.Where(x => x.status == 'A') on o.id = od.orderid
select new { Order = o, Details = od}