2011-11-26 101 views
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)) 

谢谢大家,和我的英语不好

+0

什么是您的具体问题?失败的地方在哪里?是否有编译错误? – Polynomial

+0

有时最好回到为什么编写SQL的意图,然后尝试用你的类模型和Linq来表达它们,而不关注1:1的翻译。使用更高效的SQL执行计划,代码生成甚至可能让您感到惊讶! –

回答

0

您还可以检查LINQPad遗憾。当然,你可以将它分解为多个LINQ查询(毕竟,执行是延迟的,所以它将作为一个单一查询执行,而不使用临时表,99%的情况应该更快)。

但在你的情况下,它可以更简单地写,用你可能已经设置了导航属性:

var result= from p in products 
      select new {Name=p.Name, 
         Id = p.Id, 
         Count = p.Factories.Where(f=> f.date <= date).Sum(f=>f.Count) 
           - p.otgrs.Where(o=> o.date <= date).Sum(o=>o.Count) 
         };