简体   繁体   中英

EF LINQ Group By and Sum

I'm trying to do select with group by and sum while selecting other columns using LINQ and i come out with this

var inputList = from c in db.InputItem
                             join o in db.ItemsDefinition on c.ItemsDefinitionID equals o.ItemsDefinitionID
                             group c by new { c.ItemsDefinitionID, o.ItemsAName } into g
                             select new
                             {
                                 Name = g.Key,
                                 Sum = g.Sum(c => c.Quantity)
                             };

what I'm trying to do is to preform this SQL statement

Select i.ItemsDefinitionID,
       ID.ItemsAName, 
       sum(Quantity) as avialable
from InputItem i 
Left Outer Join ItemsDefinition ID On i.ItemsDefinitionID=ID.ItemsDefinitionID
group by i.ItemsDefinitionID,ID.ItemsAName

Warm Thanks

You don't really need to do manual joins in EF if your relationships are properly defined in the model.

This query will suffice

var result = db.ItemsDefinition.Select(id => new { id.ItemsDefinitionID, 
        id.ItemsAName, Quantity = id.Items.Sum(i => i.Quantity) });

Either leave the SQL generation to EF or stop using EF. There's no point in using an ORM if you keep worrying about the queries it will generate.

you can do this way too:

var inputList = d.InputItem
    .GroupBy(s =>s.ItemsDefinitionID, s.ItemsDefinition.AName)
    .Select(g => new
    {
        ItemsDefinitionID=g.Key.ItemsDefinitionID,
        Name = g.Key.AName,
        Available= g.Sum(s =>s.Quantity),
       
    })
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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