Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple Group By and Count in LINQ Entity Framework

I am facing one simple question here and since I am new in LINQ, I really need someone help.

I have one SQL Query to Sum Amount based on Client ID, CommissionName and Date only from a DateTime. Here is the SQL Query :

SELECT ClientId, CommisionName , CAST(Date AS DATE) DateOnly , sum(Amount)
  FROM [MyDB].[dbo].[Commission] group by ClientId, CAST(Date AS DATE), CommisionName

What I got for Grouping in LINQ is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 var data = from c in await _context.Commission.ToListAsync() 
                   group c by new
                   {
                       c.CommisionName,
                       c.ClientId,
                       c.Date,
                   } into gcs
                   select new
                   {
                       ClientId = gcs.Key.ClientId,
                       CommissionName = gcs.Key.CommisionName,
                       Date = gcs.Key.Date,
                   };

But I am still dont have reference if I need to summarize the Amount.

Please I need someone reference.. Thank you

>Solution :

With gcs.Sum(x => x.Amount) to perform the sum of the Amount.

Note that your current query will query all the records and perform group on the memory side.

To perform the query with group on the database side, the LINQ query should be below:

var data = await (from c in _context.Commission 
                   group c by new
                   {
                       c.CommisionName,
                       c.ClientId,
                       c.Date.Date,
                   } into gcs
                   select new
                   {
                       ClientId = gcs.Key.ClientId,
                       CommissionName = gcs.Key.CommisionName,
                       Date = gcs.Key.Date,
                       Amount = gcs.Sum(x => x.Amount)
                   }
                   ).ToListAsync();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading