简体   繁体   English

LINQ to EF,左联接和group by子句

[英]LINQ to EF, Left Join and group by clause

I have this SQL: 我有这个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

How can I translate this into Linq? 如何将其翻译成Linq? I'm stuck with this code: 我坚持下面的代码:

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))

Thank to everyone, and sorry for my bad english 谢谢大家,对不起我的英语不好

You can also check LINQPad . 您也可以检查LINQPad Of course, you can split this into multiple LINQ queries (after all, the execution is deferred, so it will be executed all as one single query, without using temporary tables. It should be faster in 99% of the cases). 当然,您可以将其拆分为多个LINQ查询(毕竟,执行是延迟的,因此它将作为一个查询全部执行,而无需使用临时表。在99%的情况下,它应该更快)。

But in your case it can be written more simply, by using navigation properties you probably have already set up: 但是在您的情况下,可以使用导航属性来更简单地编写它:

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)
                       };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM