LINQ to EF,Left Join和group by子句

时间:2011-11-26 14:54:30

标签: c# .net linq entity-framework linq-to-entities

我有这个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))

感谢大家,对不起我的坏英语

1 个答案:

答案 0 :(得分: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)
                       };