Library

Volume 3 · .NET & C# Deep Dive

Notebook
Sign in

Section 3

Entity Framework Core (IQueryable vs IEnumerable, N+1 problem, performance tuning)

1,058 words · about 5 min

3.1 IQueryable vs IEnumerable

// IEnumerable<T> — LINQ to Objects (in-memory)
IEnumerable<Order> orders = dbContext.Orders;
var filtered = orders.Where(o => o.Total > 100);
// Loads ALL orders into memory, then filters in C#

// IQueryable<T> — LINQ to SQL (translated to SQL)
IQueryable<Order> ordersQ = dbContext.Orders;
var filteredQ = ordersQ.Where(o => o.Total > 100);
// Translates to: SELECT * FROM Orders WHERE Total > 100

// RULE: Keep as IQueryable as long as possible, materialize late
public async Task<List<OrderDto>> GetOrdersAsync(decimal minTotal, int page, int pageSize)
{
    return await dbContext.Orders
        .Where(o => o.Total > minTotal)       // SQL WHERE
        .OrderByDescending(o => o.CreatedAt)  // SQL ORDER BY
        .Skip((page - 1) * pageSize)          // SQL OFFSET
        .Take(pageSize)                       // SQL LIMIT
        .Select(o => new OrderDto             // SQL SELECT (projection)
        {
            Id = o.Id,
            Total = o.Total,
            Status = o.Status.ToString()
        })
        .ToListAsync();                       // Execute SQL
}

Disaster scenario: casting a DbSet<T> to IEnumerable early silently forces the whole table into memory before filtering:

IEnumerable<Order> orders = dbContext.Orders; // Still IQueryable internally, but typed as IEnumerable
var result = orders.Where(o => o.Total > 100).ToList();
// This loads ALL orders into memory, then filters in C#!

This single mistake can turn a 5ms indexed query into a 30-second full-table scan that crashes the service under load.

Expression trees underpin this: Expression<Func<T,bool>> is a data structure representing code that EF Core’s provider walks and translates to SQL; a plain Func<T,bool> is already-compiled IL that cannot be translated — passing the wrong one silently downgrades a query to IEnumerable semantics.

3.2 The N+1 Problem

// N+1: one query for orders, then one query PER order for its items
var orders = await dbContext.Orders.ToListAsync();
foreach (var order in orders)
{
    var items = await dbContext.Entry(order).Collection(o => o.Items).LoadAsync(); // N queries!
}

// Fix 1: eager loading with Include
var orders = await dbContext.Orders
    .Include(o => o.Items)
    .ToListAsync();

// Fix 2: projection — select only what you need, EF Core generates one JOIN
var orderSummaries = await dbContext.Orders
    .Select(o => new OrderSummaryDto
    {
        Id = o.Id,
        ItemCount = o.Items.Count
    })
    .ToListAsync();

// Fix 3: split query when Include with multiple collections causes a cartesian explosion
var orders = await dbContext.Orders
    .Include(o => o.Items)
    .Include(o => o.Payments)
    .AsSplitQuery() // Runs as 3 separate SQL queries instead of one huge JOIN
    .ToListAsync();

3.3 Performance Tuning

// 1. AsNoTracking for read-only queries — skips change tracking overhead
var orders = await dbContext.Orders
    .AsNoTracking()
    .Where(o => o.Status == OrderStatus.Shipped)
    .ToListAsync();

// 2. Compiled queries for hot paths called extremely often
private static readonly Func<AppDbContext, int, Task<Order?>> GetOrderById =
    EF.CompileAsyncQuery((AppDbContext ctx, int id) =>
        ctx.Orders.FirstOrDefault(o => o.Id == id));

// 3. Batch updates/deletes (EF Core 7+) — avoid loading entities just to update them
await dbContext.Orders
    .Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt < cutoff)
    .ExecuteDeleteAsync();

await dbContext.Orders
    .Where(o => o.Status == OrderStatus.Pending)
    .ExecuteUpdateAsync(setters => setters.SetProperty(o => o.Status, OrderStatus.Expired));

// 4. Avoid loading entire entities when a projection suffices
var totals = await dbContext.Orders
    .Where(o => o.CustomerId == customerId)
    .Select(o => o.Total)   // Only fetches the Total column
    .SumAsync();

// 5. Indexing — configure via Fluent API to match query patterns
modelBuilder.Entity<Order>()
    .HasIndex(o => new { o.CustomerId, o.Status })
    .HasDatabaseName("IX_Orders_CustomerId_Status");

Interview Q&A — Section 3

Q1: Explain the difference between IEnumerable and IQueryable. What happens if you use the wrong one with EF Core?

A: IEnumerable<T> executes LINQ operations in-memory, on data already materialized. IQueryable<T> builds an expression tree that the EF Core provider translates into SQL and executes on the database. If a DbSet<T> is accidentally typed/cast as IEnumerable before filtering, EF Core pulls the entire table into memory first and then filters in C# — a query that should return a handful of rows can instead load millions, turning a 5ms query into a 30-second outage. The rule: keep the query as IQueryable for as long as possible and only materialize (ToList/ToListAsync/FirstOrDefault) at the very end.

Q2: How do you detect and fix the N+1 query problem in EF Core?

A: Detect it by enabling EF Core’s logging (.LogTo(Console.WriteLine, LogLevel.Information)) or a SQL profiler in staging and watching for repeated near-identical queries per row. Fix with .Include() for eager loading of a known-needed collection, with .AsSplitQuery() when multiple Includes would otherwise produce a cartesian-product explosion, or — often the best option — with a .Select() projection that asks the database for exactly the shape you need in one query.

Q3: What performance techniques do you reach for on a read-heavy EF Core endpoint?

A: AsNoTracking() to skip change-tracking overhead on read-only queries; projections (.Select()) instead of loading full entity graphs; compiled queries for extremely hot, repeatedly-executed queries; proper indexes matched to the actual WHERE/ORDER BY patterns; and pagination (Skip/Take) pushed into SQL rather than materialized client-side. For bulk writes I use ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+) to avoid loading entities into the change tracker just to update or delete them.

Q4: What’s the difference between Expression<Func<T,bool>> and Func<T,bool>, and why does it matter for EF Core?

A: Func<T,bool> is compiled IL — a delegate that can only be invoked, not inspected. Expression<Func<T,bool>> is a data structure representing the code itself (an expression tree) that a LINQ provider like EF Core can walk and translate into SQL. If you accidentally pass a Func where an Expression was expected (or materialize to IEnumerable first), EF Core can no longer translate the predicate to SQL and instead evaluates it client-side after pulling all rows — a subtle but severe performance bug.