How would you optimize an EF Core query that's generating inefficient SQL, and what tools help identify the actual generated SQL?
Short answer
Use context.Database.Log or the built-in logging (configuring the Microsoft.EntityFrameworkCore.Database.Command category to Information/Debug level) to see the exact SQL EF Core generates, or use EF Core's ToQueryString() method on an IQueryable to inspect the SQL without…
Advertisement
AModel answer
Use context.Database.Log or the built-in logging (configuring the Microsoft.EntityFrameworkCore.Database.Command category to Information/Debug level) to see the exact SQL EF Core generates, or use EF Core's ToQueryString() method on an IQueryable to inspect the SQL without executing it -- common optimizations include adding AsNoTracking() for read-only queries, using Select() to project only needed columns instead of loading full entities, using Include() strategically to avoid N+1 while avoiding over-fetching with excessive includes, and adding appropriate database indexes for frequently filtered/sorted columns.
var query = context.Products.Where(p => p.Category == "Electronics").OrderBy(p => p.Price);
Console.WriteLine(query.ToQueryString()); // prints the exact generated SQL without executing
// Optimized: project only needed columns
var summaries = await context.Products
.Where(p => p.Category == "Electronics")
.Select(p => new { p.Id, p.Name, p.Price }) // avoids loading full entity
.ToListAsync();Real-world example
A team diagnosing a slow product listing endpoint uses ToQueryString() to discover EF Core was selecting all 40 columns of a wide Product table when the UI only displayed 3 fields, fixing it with a targeted Select() projection.
Likely follow-ups
- How do you enable EF Core's built-in query logging in appsettings.json?
- What's the performance difference between projecting with Select() versus loading full entities?
Related topics