【发布时间】:2011-11-26 14:54:29
【问题描述】:
我有这个 SQL:
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))
谢谢大家,对不起我的英语不好
【问题讨论】:
-
您的具体问题是什么?哪里失败了?有编译错误吗?
-
有时最好回到编写 SQL 的意图,然后尝试根据您的类模型和 Linq 来表达这些意图,而不必太在意 1:1 的翻译。更高效的 SQL 执行计划甚至可能让代码生成让您大吃一惊!
标签: c# .net linq entity-framework linq-to-entities