Why Lazy Loading is a Performance Trap in ASP.NET Core
We’ve all been there. Your new API endpoint flies on your machine, returning customer orders in 50ms. You deploy it, and suddenly… it’s taking two seconds. The logs don’t show any obvious errors, but your app is crawling. The culprit is often a feature designed for convenience: lazy loading.
Lazy loading in Entity Framework Core feels like magic during development, but it can hide a massive performance tax that will absolutely cripple your application at scale.
So What Exactly is Lazy Loading?
Lazy loading means EF Core automatically grabs related data from the database only when you access it. Instead of you explicitly telling EF what you need upfront, EF Core reacts to your code. When you touch a navigation property for the first time, boom, it fires off a new database query to get that data.
Sounds handy, right? The problem is that each of these property accesses can trigger a separate, hidden database round-trip. What looks like a simple line of C# can become a silent storm of SQL queries.
The Sneaky Performance Killer: The N+1 Query Problem
The most common side effect of lazy loading is the infamous N+1 query problem. It starts with one simple query and then spirals.
Take a look at this standard ASP.NET Core controller action that fetches 50 orders:
public async Task<IActionResult> GetOrderSummary()
{
var orders = await _context.Orders.Take(50).ToListAsync();
// The problem kicks in right here, usually during serialization
var …