Lesson 6 of 9
LINQ - Production Query Patterns
LINQ (Language Integrated Query) is the backbone of data querying in C# - used directly with EF Core to generate SQL, and with in-memory collections. Understanding deferred execution, performance pitfalls, and expression trees is essential for writing efficient database queries.
Deferred Execution & Query Composition
using System.Linq;
// ━━ Deferred execution - query is NOT executed until enumerated ━━
IQueryable<Product> query = dbContext.Products
.Where(p => p.IsActive && p.Price > 0); // no SQL yet - just expression tree
if (!string.IsNullOrEmpty(searchTerm))
query = query.Where(p => p.Name.Contains(searchTerm)); // appended - still no SQL
if (categoryId is not null)
query = query.Where(p => p.CategoryId == categoryId); // still building
var sorted = query.OrderBy(p => p.Name); // still no SQL
// SQL is generated and executed ONLY here:
var results = await sorted
.Select(p => new ProductDto(p.Id, p.Name, p.Price)) // project before loading
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(ct); // ← EXECUTES SQL
// ━━ N+1 problem - the most common EF Core performance bug ━━
// BAD: loads all orders, then one query per order to get customer
var orders = await dbContext.Orders.ToListAsync(); // 1 query
foreach (var order in orders)
{
var name = order.Customer.Name; // N queries (lazy load!) ← N+1!
}
// GOOD: eager load with Include - 1 query with JOIN
var orders2 = await dbContext.Orders
.Include(o => o.Customer) // JOIN in single query
.Include(o => o.Items)
.ThenInclude(i => i.Product) // nested join
.AsNoTracking() // read-only: skip change tracking
.ToListAsync(ct);
// ━━ Projection - SELECT only what you need ━━
// Never load entire entity if you only need 2 columns
var names = await dbContext.Products
.Where(p => p.CategoryId == categoryId)
.Select(p => new { p.Id, p.Name }) // only 2 columns in SQL
.ToListAsync(ct);
// Placeholder
record ProductDto(string Id, string Name, decimal Price);Tip
Tip
Practice LINQ Production Query Patterns 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 Production Query Patterns 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 Production Query Patterns 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?