Tutorials Entity Framework Core Tutorial
Aggregation with LINQ in EF Core
Aggregation with LINQ in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 39 of 100
Aggregation with LINQ in EF Core
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Data & queries · ~6 min · Module 4: LINQ
What is this?
Aggregation functions — Count, Sum, Average, Min, Max — compute scalar results from sets. Async versions execute single-value SQL aggregates.
Why should you care?
ShopNest homepage shows product count and average rating without loading every row into the API process.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
var stats = await _context.Products
.Where(p => p.CategoryId == catId && p.IsPublished)
.GroupBy(p => 1)
.Select(g => new CategoryStatsDto
{
ProductCount = g.Count(),
AvgPrice = g.Average(p => p.Price),
MaxPrice = g.Max(p => p.Price)
})
.FirstAsync();
What happened?
- GroupBy constant 1 aggregates entire filtered set into one row.
- Count/Average/Max become SQL aggregates returning scalars.
Practice next
- Use CountAsync on filtered IQueryable for existence totals.
- Combine aggregates in one Select to avoid multiple round trips.
- Handle empty sets — Average on zero rows throws.
- Add Min(p => p.StockQty) for inventory alert threshold.
- Use Sum on OrderItems for category revenue without GroupBy when single total needed.
Remember
Aggregates run server-side in SQL. Batch aggregates in one query when possible. Use async scalar methods for API endpoints.
ShopNest category header stats
Category page header shows count and average price from one aggregate query.
Outcome: Header renders instantly without scanning full product list in API.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!