Saturday, August 24, 2019

Entity Framework Core GROUP BY (Grouping)

In the previous posts we saw on how to get data from a SQL Server table using EF Core context, how to filter data using various types of filters and how to Sort the data using sorting keys. In this post we shall see on how to perform Aggregate operations like COUNT, MAX, MIN etc by Grouping rows based on keys. This is similar to the GROUP BY clause in SQL Server.

Let’s start with a GROUP BY query which will get the count of employees in each of the City in the Employee table.

SQL Query
SELECT City, Count(1) FROM [dbo].[Employee] GROUP BY City


LINQ Query
            var EmployeeGroup = _context.Employee
                                .GroupBy(x => x.City)

                                .Select(g => new { name = g.Key, count = g.Count() });

The above query will produce the following result structure in the EmployeeGroup object.


Similarly we can perform other Aggregate operations like Sum, Mix, Max etc by grouping rows based on a Key.

Search Flipkart Products:
Flipkart.com

No comments: