How to Find and Fix N+1 Queries in EF Core
The API was screaming. A single endpoint, perfectly fine on my machine, was bringing our database to its knees in production. After digging through the logs, I found the culprit: one request was generating 241 separate SQL queries.
This one burned me badly early in my career. It’s a classic trap that every developer using an ORM like Entity Framework Core will eventually fall into: the N+1 query problem. It’s silent in development but absolutely lethal at scale.
So, What’s an N+1 Query Anyway?
It’s a sneaky performance bug. You ask EF Core for a list of items, and it happily obliges with one query. That’s the “1”.
Then, you loop through that list, and for each item, you access a related property (like a post’s author). If you haven’t told EF Core to load that related data upfront, it goes back to the database for every single item. That’s the “N”.
So, to get 100 blog posts and their authors, you end up with:
- 1 query to get the 100 posts.
- 100 more queries to get each post’s author.
- Total: 101 queries for what should have been a simple operation.
In that production disaster I mentioned, fixing the N+1 pattern dropped the query count from 241 to just 3. The response time fell by over 85%.
How to Spot an N+1 Ambush
You can’t fix what you can’t see. Here are my go-to methods for hunting down these hidden performance killers.
1. Just Watch the Logs
This is the most direct way to see the problem. Turn on …