LINQ到EF,左连接和分组子句

本文关键字:子句 连接 EF LINQ | 更新日期: 2023-09-27 18:15:43

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

谢谢大家,很抱歉我的英语不好

LINQ到EF,左连接和分组子句

您也可以检查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)
                       };