Sub topic 19
Inspecting Generated SQL and Improving Performance
EF Core writes SQL for you. That saves time, but it also hides what is sent to the database. A query that looks short in C# can turn into many database calls, or into one call that returns far more data than you need. This chapter shows how to see the SQL EF Core produces and how to fix the most common slow patterns.
The examples use the Blog and Post classes and the SQLite database from earlier chapters.
Why Look at the SQL?
SQL (Structured Query Language) is the language databases understand. Every LINQ query and every SaveChangesAsync call becomes one or more SQL commands.
A round trip is one request from your app to the database and the reply that comes back. Each round trip takes time, even when the database is on the same machine. The fewer round trips you make, and the less data each one returns, the faster your app runs.
You can't judge either of those from the C# code alone, so you need to look at the SQL.
Logging Every Command with LogTo
LogTo is a method on the options builder. It sends EF Core's log messages to any method that accepts a string, such as Console.WriteLine.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
public class LoggingBloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options
.UseSqlite("Data Source=blogging.db")
.LogTo(
Console.WriteLine,
new[] { DbLoggerCategory.Database.Command.Name },
LogLevel.Information);
}The second argument is a log category filter. It keeps only messages about executed database commands and drops the rest of EF Core's output, so you see just the SQL.
Run a simple query:
using var db = new LoggingBloggingContext();
var blogs = await db.Blogs
.Where(b => b.Url.Contains("example"))
.ToListAsync();The console shows something like this:
SELECT "b"."BlogId", "b"."Url"
FROM "Blogs" AS "b"
WHERE instr("b"."Url", 'example') > 0Each logged command is one round trip. If you see the same command printed again and again, you have found a problem.
Seeing One Query with ToQueryString
Sometimes you want the SQL for one query without logging everything. ToQueryString returns the SQL as a string and does not run the query.
using var db = new LoggingBloggingContext();
var query = db.Blogs
.Where(b => b.Url.StartsWith("https://"))
.OrderBy(b => b.Url);
Console.WriteLine(query.ToQueryString());ToQueryString works on any query that has not run yet. Call it before methods like ToListAsync or FirstAsync, because those run the query and return results instead of a query object.
The N+1 Query Problem
The N+1 problem happens when your code runs one query to get a list, then one more query for each item in that list. With 100 blogs, you make 101 round trips.
Here is code that causes it:
using var db = new LoggingBloggingContext();
var blogs = await db.Blogs.ToListAsync(); // 1 query
foreach (var blog in blogs)
{
int count = await db.Posts
.CountAsync(p => p.BlogId == blog.BlogId); // N more queries
Console.WriteLine($"{blog.Url}: {count} posts");
}The code looks harmless. With logging turned on, you would see one SELECT for blogs and then one SELECT COUNT(*) per blog.
The fix is to ask for everything in one query. A projection uses Select to shape the results into only what you need:
using var db = new LoggingBloggingContext();
var summaries = await db.Blogs
.Select(b => new { b.Url, PostCount = b.Posts.Count })
.ToListAsync(); // 1 query
foreach (var s in summaries)
{
Console.WriteLine($"{s.Url}: {s.PostCount} posts");
}EF Core turns b.Posts.Count into a subquery inside a single SQL statement. The database does all the counting in one round trip.
If you need the full related entities and not just a count, use Include, which you met in the chapter on loading related data. It also loads everything in one query.
Fetching Less Data
A second common problem is over-fetching, which means loading columns or rows you never use.
Suppose you only need post titles. This query loads every column, including the full Content of every post:
var posts = await db.Posts.ToListAsync();
var titles = posts.Select(p => p.Title).ToList();The Select here runs in memory, after all the data has already arrived. Move it before ToListAsync so it becomes part of the SQL:
var titles = await db.Posts
.Select(p => p.Title)
.ToListAsync();Now the SQL is SELECT "p"."Title" FROM "Posts" AS "p". Only one column travels over the connection.
The same rule applies to filtering. Put Where before ToListAsync so the database filters the rows, not your app.
Skipping Tracking for Read-Only Queries
As the change tracking chapter explained, EF Core keeps a copy of every entity it loads so it can detect changes later. That costs memory and time. When you only display data and never change it, use AsNoTracking:
var blogs = await db.Blogs
.AsNoTracking()
.Where(b => b.Url.StartsWith("https://"))
.ToListAsync();The SQL is the same. The saving happens inside your app, because EF Core skips building tracking records. Projections into anonymous types or other non-entity classes are never tracked, so they don't need AsNoTracking.
Quick Reference
| Symptom in the log | Likely cause | Fix |
|---|---|---|
| Same query repeated many times | N+1 pattern in a loop | Use `Select` projection or `Include` |
| `SELECT` lists every column | Over-fetching | Add `Select` before running the query |
| No `WHERE` clause, filtering done later | `Where` placed after `ToListAsync` | Move `Where` before `ToListAsync` |
| Query is fine but memory use is high | Tracking read-only data | Add `AsNoTracking()` |
| Many `UPDATE` commands for one change | Updating entities one by one | Use `ExecuteUpdateAsync` |
A Simple Habit
- Turn on
LogTowhile you build a feature. - Run the feature once and count the commands in the console.
- Read each
SELECTand check that it asks only for the columns and rows you need. - Fix what you find, then run again to confirm the log is shorter.
This takes a few minutes and catches most performance problems before users notice them.
Exercise
You load 50 blogs with db.Blogs.ToListAsync(), then inside a foreach loop you call db.Posts.Where(p => p.BlogId == blog.BlogId).ToListAsync() for each blog. How many round trips does this make, what is this problem called, and how can you fix it?
Show answer
It makes 51 round trips: one for the blogs and one for each of the 50 blogs. This is the N+1 query problem. Fix it by loading posts together with blogs in one query, for example await db.Blogs.Include(b => b.Posts).ToListAsync(), or by using Select to project only the post data you need.
Exercise
What is the difference between ToQueryString() and LogTo(...)?
Show answer
ToQueryString() returns the SQL for one query as a string without running it. LogTo(...) is set up once on the context and writes every SQL command that is actually run, including those from SaveChangesAsync.
Exercise
Why is db.Posts.Select(p => p.Title).ToListAsync() faster than (await db.Posts.ToListAsync()).Select(p => p.Title).ToList()?
Show answer
In the first version, Select becomes part of the SQL, so the database returns only the Title column. In the second, every column of every post, including the long Content text, is loaded into memory first, and the titles are picked out afterward.