Lesson 4 of 8
LINQ Query Patterns & Performance
EF Core translates LINQ to SQL. Understanding which LINQ methods translate to efficient SQL-and which cause client-side evaluation, N+1 queries, or full table scans-is critical for production performance. A single bad LINQ query can bring down your database under load.
Production LINQ Patterns
// ━━ Split queries - avoids Cartesian explosion on multi-Include ━━
// Without splitting: one query with JOIN creates row duplication (Order × Items × Products)
// With splitting: 3 separate queries - much smaller result set
var orders = await dbContext.Orders
.Include(o => o.Customer)
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.AsSplitQuery() // 3 queries instead of 1 massive Cartesian product
.AsNoTracking() // read-only: skip change tracking overhead
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.CreatedAt)
.Take(50)
.ToListAsync(ct);
// ━━ Compiled queries - cache query plan (fastest for hot paths) ━━
// Define once at app startup - compiled plan reused on every call
private static readonly Func<AppDbContext, Guid, CancellationToken, Task<Product?>>
GetProductById = EF.CompileAsyncQuery(
(AppDbContext db, Guid id, CancellationToken ct) =>
db.Products.FirstOrDefault(p => p.Id == id));
// Use in service:
var product = await GetProductById(dbContext, productId, ct);
// No LINQ re-compilation on every call - significant speedup for high-QPS endpoints
// ━━ Raw SQL with EF Core - when LINQ can't express it ━━
// Safe parameterized raw SQL:
var search = "widget";
var products = await dbContext.Products
.FromSqlRaw("SELECT * FROM Products WHERE CONTAINS(Name, {0})", search) // SQL Server FTS
.AsNoTracking()
.ToListAsync(ct);
// ExecuteSqlRaw for non-query operations
await dbContext.Database.ExecuteSqlRawAsync(
"UPDATE Products SET Stock = Stock - {0} WHERE Id = {1}", 1, productId);
// ━━ Bulk operations (.NET 7+ EF Core ExecuteUpdateAsync/ExecuteDeleteAsync) ━━
// Without loading entities - direct UPDATE SQL
var updatedCount = await dbContext.Products
.Where(p => p.CategoryId == categoryId && p.Price > 100)
.ExecuteUpdateAsync(setters => setters
.SetProperty(p => p.UpdatedAt, DateTime.UtcNow)
.SetProperty(p => p.IsOnSale, true), ct);
// Direct DELETE without loading
await dbContext.Products
.Where(p => p.CreatedAt < DateTime.UtcNow.AddYears(-5) && !p.HasOrders)
.ExecuteDeleteAsync(ct);
// ━━ GroupBy - must project before calling ToList ━━
var salesByCategory = await dbContext.Products
.GroupBy(p => p.CategoryId)
.Select(g => new
{
CategoryId = g.Key,
TotalProducts = g.Count(),
AveragePrice = g.Average(p => p.Price),
TotalRevenue = g.Sum(p => p.Price * p.SoldCount)
})
.ToListAsync(ct);
// Placeholder additions
class Product2 { public Guid Id { get; set; } public Guid CategoryId { get; set; } public decimal Price { get; set; } public bool HasOrders { get; set; } public int SoldCount { get; set; } public bool IsOnSale { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } }Tip
Tip
Practice LINQ Query Patterns Performance in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of LINQ Query Patterns Performance from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with LINQ Query Patterns Performance is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?