Sub topic 18
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. This chapter shows how to see that SQL, how to fix two common slow patterns, and how to test your data code.
Seeing the SQL EF Core Sends
Logging is a record of what a program does while it runs. The LogTo method tells EF Core to write every SQL command to a place you choose, such as the console.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
public class LoggingBloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options
.UseSqlite("Data Source=blogging.db")
.LogTo(Console.WriteLine, LogLevel.Information);
}
// Elsewhere
var query = db.Blogs.Where(b => b.Url.Contains("example"));
Console.WriteLine(query.ToQueryString());ToQueryString shows the SQL for one query without running it. Use it when you want to check a single query. Use LogTo when you want to watch everything.
The N+1 Problem
An 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, that is 101 trips to the database.
// Slow: 1 query for blogs, then 1 query per blog
var blogs = await db.Blogs.ToListAsync();
foreach (var blog in blogs)
{
int count = await db.Posts.CountAsync(p => p.BlogId == blog.BlogId);
Console.WriteLine($"{blog.Url}: {count}");
}
// Fast: one query that returns only what you need
var summary = await db.Blogs
.Select(b => new { b.Url, PostCount = b.Posts.Count })
.ToListAsync();If the log shows the same query over and over with only the value changing, you probably have an N+1 problem.
Two More Quick Wins
- Add
AsNoTracking()to read-only queries. EF Core then skips the work of watching those objects for changes. - Use
Selectto fetch only the columns you need, instead of whole rows.
Testing Data Access Code
A test is code that checks that other code works. To test EF Core code, a simple choice is SQLite in memory. The database exists only while the connection is open, so each test starts fresh.
This example uses xUnit, a test framework, and the AppDbContext from the dependency injection chapter, which accepts options in its constructor.
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Xunit;
public class BlogTests
{
[Fact]
public async Task Adding_a_blog_saves_it()
{
using var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
using (var db = new AppDbContext(options))
{
db.Database.EnsureCreated();
db.Blogs.Add(new Blog { Url = "https://example.com" });
await db.SaveChangesAsync();
}
using (var db = new AppDbContext(options))
{
Assert.Equal(1, await db.Blogs.CountAsync());
}
}
}EnsureCreated builds the tables from your model without migrations. The test uses a second context to check the data. That way it reads from the database instead of from objects the first context already holds in memory.
Exercise
Your log shows "SELECT ... FROM Posts WHERE BlogId = @p0" printed 50 times in a row. What is wrong, and how do you fix it?
Show answer
It is an N+1 problem: the code runs one query per blog. Fix it by loading the data in one query, for example with Include(b => b.Posts) or a Select that projects b.Posts.Count.
Exercise
Why does the test open the SqliteConnection itself instead of passing a connection string to UseSqlite?
Show answer
An in-memory SQLite database is deleted when its connection closes. Keeping one open connection lets both contexts in the test share the same database.