0

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

Serge
  • 40,935
  • 4
  • 18
  • 45
  • 1
    What is the question? – Serge Feb 05 '21 at 10:58
  • Perhaps my [SQL to LINQ Recipe](https://stackoverflow.com/questions/49245160/sql-to-linq-with-multiple-join-count-and-left-join/49245786#49245786) might help you. – NetMage Feb 06 '21 at 00:54

2 Answers2

0

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.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
0

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();
Serge
  • 40,935
  • 4
  • 18
  • 45