See the dramatic performance difference between optimized and unoptimized queries
// Load ALL data first
var all = await context.Products
.ToListAsync();
// Then filter in memory
var filtered = all
.Where(p => p.Price > 500)
.ToList();
Loads entire dataset into memory
// Filter in database
var filtered = await context.Products
.Where(p => p.Price > 500)
.ToListAsync();
Only loads filtered results
// Get categories first
var categories = await context.Products
.Select(p => p.Category)
.Distinct()
.ToListAsync();
// Then count each category
foreach (var cat in categories)
{
var count = await context.Products
.CountAsync(p => p.Category == cat);
}
N+1 queries (1 + 10 = 11 queries)
// Single GroupBy query
var stats = await context.Products
.GroupBy(p => p.Category)
.Select(g => new
{
Category = g.Key,
Count = g.Count()
})
.ToListAsync();
Single optimized query