Home > Back-end >  How to convert this sql query into linq query. I am stuck at the group by and sum part
How to convert this sql query into linq query. I am stuck at the group by and sum part

Time:05-11

My SQL query looks something like this : The SQL query returns the revenue associated with every colorwaysid present

select p.colorwaysid,sum(oivs.actItemvalue oivs.custom) as revenue 
from Product p inner join eshakti_corp..orderitemvaluesplit oivs on p.productid = oivs.productid
inner join eshakti_corp..orders o on oivs.orderid = o.orderid
where colorwaysid is not null and o.crdate >= '4/1/2022' and o.crdate <= '4/30/2022'
group by p.colorwaysid order by revenue desc

and I have so far done this in LINQ C#

from product in eshaktiDb.Products 
join oivs in corpDb.OrderitemvalueSplits on product.ProductId equals oivs.Productid
join order in corpDb.Orders on oivs.Orderid equals order.OrderID
where product.ColorWaysId != null && order.CrDate >= fromDate && order.CrDate <= toDate

Please help me in creating the complete Linq query. Thanks!

CodePudding user response:

group by part is obvious:

var query = 
    from product in eshaktiDb.Products 
    join oivs in corpDb.OrderitemvalueSplits on product.ProductId equals oivs.Productid
    join order in corpDb.Orders on oivs.Orderid equals order.OrderID
    where product.ColorWaysId != null && order.CrDate >= fromDate && order.CrDate <= toDate
    group ovis by p.colorwaysid into g
    select new
    {
        colorwaysid = g.Key,
        revenue = g.Sum(o => o.actItemvalue   o.custom)
    };

Note, that if you have correctly configured navigation properties, joins can be omitted.

  • Related