2
组我有这样的SQL:LINQ到EF,左联接和条款
select o.prod_id, SUM(o.[count]) as [count]
into #otgr
from otgr o
where o.[date]<= @date
group by o.prod_id
select f.prod_id, SUM(f.[count]) as [count]
into #factory
from factory f
where f.[date]<= @date
group by f.prod_id
select p.name, p.id, f.[count] - ISNULL(o.[count],0) as av_count
from products p
join #factory f on f.prod_id = p.id
left join #otgr o on o.prod_id = p.id
where f.[count] - ISNULL(o.[count],0) > 0
我怎么能翻译成Linq的呢?我坚持用这个代码:
from otgrr in db.otgr
where otgrr.date <= date
group otgrr by otgrr.prod_id into otgrs
from fac in db.factory
where fac.date <= date
group fac by fac.prod_id into facs
from prod in db.products
join fac2 in facs on prod.id equals fac2.Key
join otg2 in otgrs.DefaultIfEmpty(new {id = 0, av_count = 0 }) on prod.id equals otg2.Key
where (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count)) > 0
select new products { id = prod.id, name = prod.name, av_count = (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count))
谢谢大家,和我的英语不好
什么是您的具体问题?失败的地方在哪里?是否有编译错误? – Polynomial
有时最好回到为什么编写SQL的意图,然后尝试用你的类模型和Linq来表达它们,而不关注1:1的翻译。使用更高效的SQL执行计划,代码生成甚至可能让您感到惊讶! –