Entity Framework Core: Find N+1 Queries Before They Slow Down Your Page

Have you ever worked with an Entity Framework Core application where a page takes too long to load, even though each individual database query executes quickly?

One possible reason is the N+1 query problem, a common performance issue where an application executes more database queries than necessary. For example, loading a list of twenty customers may require one query, but retrieving their related order information could trigger another twenty queries.

Although each query may be fast, the additional database round trips can significantly affect the application’s overall performance, especially as the amount of data increases.

In this article, we’ll explore what the N+1 query problem is, how to identify it in Entity Framework Core, and how to avoid unnecessary database queries to improve application performance.

 

Make the extra requests visible

Inspect EF Core command logging or an appropriate application trace in a development environment. Count the database commands associated with one page request and look for a repeated statement whose parameter changes for each customer.

Do not enable sensitive-data logging indiscriminately in production. Query parameters can contain personal or confidential values. Capture enough evidence to identify the pattern while respecting the application’s logging controls.

Lazy loading can create this behaviour when configured and triggered through navigation properties. Explicit database queries inside a loop can produce the same pattern even when lazy loading is disabled.

 

Request the shape the page needs

If the page only displays an identifier, a name and an order count, it does not need complete customer and order objects.

This illustration assumes a mapped Customers set with an Orders navigation property and the Microsoft.EntityFrameworkCore namespace:

var customers = await context.Customers
    .AsNoTracking()
    .OrderBy(c => c.CustomerId)
    .Take(20)
    .Select(c => new
    {
        c.CustomerId,
        c.Name,
        OrderCount = c.Orders.Count()
    })
    .ToListAsync();

With a compatible SQL Server provider and mapping, this query shape is intended to calculate the count in the database instead of fetching each customer’s orders separately. Inspect the generated SQL and command count in your actual EF Core version.

AsNoTracking communicates that the operation is read-only, although this projection contains only scalar values and does not materialise tracked entity instances anyway. The main change is the projection and server-side aggregation.

 

Use eager loading when related entities are needed

If the page genuinely needs order details, an appropriate Include can make related-data loading explicit. However, including several collections can substantially expand the result shape and repeat parent data.

Split queries can address some result-expansion problems, but they use multiple commands and have their own consistency and performance considerations. Neither “always Include” nor “always use split queries” is a reliable universal rule.

Choose based on the required data, the number of related rows and the application’s latency conditions.

 

Test with realistic relationships

A development database where each customer has one order may hide the issue. Test customers with no orders, a few orders and many orders. Also test under network latency representative of the deployed application.

Record the command count, rows and columns returned, database duration, and complete request duration. Confirm that the new query returns the same business result. Reducing round trips is useful only if the revised result remains correct and the database work remains reasonable.

 

Keep the fix close to the use case

A reusable repository method that always loads every relationship can make one screen easier while making many others slower. Prefer a query or projection designed around the page’s actual requirements.

When an EF Core screen slows down, inspect the conversation with the database. The critical evidence may be twenty unnecessary requests rather than a single missing index.

 

Technical references

 

Continue learning

To build your foundation in connecting .NET applications to SQL Server with Entity Framework, explore my course Entity Framework: Getting Started – Complete Beginners Guide on Udemy. Review the curriculum and preview to see whether it fits your next learning goal.

 

Read Also

 

Stay connected

Subscribe to the GnoelixiAI Hub newsletter on LinkedIn for practical insights on AI, data and technology.

Watch more on YouTube: SQLNetHub TV and my personal channel.

 

Rate this article: (No Ratings Yet)

Originally published on SQLNetHub.
© SQLNetHub