📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: an order repository exposes GetAll() as IEnumerable<Order> and filters on it, loads each order's lines in a loop, relies on lazy loading for the customer, filters by Year and Month of CreatedAt, includes a blob Attachments collection and tracks everything, all with synchronous calls. What do you flag across EF Core and SQL Server, ranked by severity, and what does the rewrite look like?

A code review of a typical slow EF Core repository: IEnumerable client-side filtering, N+1 and lazy loading, non-SARGable date predicates, blob over-fetching, unnecessary tracking, missing indexes and sync I/O, ranked by severity with a measured rewrite.

Senior CodeReview Advanced code-review ef-core n-plus-one performance sargability sql-server

🎯 Key points

  • Returning IEnumerable<Order> from GetAll() binds every later Where/Select to LINQ to Objects: EF runs SELECT * FROM Orders and the filter runs in memory
  • N+1: per-order line queries plus lazy-loaded Customer, so one request makes hundreds of round trips
  • CreatedAt.Year/Month translates to DATEPART: non-SARGable, so it scans; a half-open range (>= start AND < nextStart) lets SQL Server seek
  • Include of a blob collection plus tracking: huge transfer, memory (LOH) and snapshot cost for a read-only list
  • Indexes to match the predicates: Customers.Number unique, Orders(CustomerId, CreatedAt DESC) INCLUDE only the projected columns, verified in the plan
  • Synchronous ToList() on a request thread blocks ThreadPool threads; use async with CancellationToken
  • Rewrite: one projected, no-tracking, paged query to a DTO, proved by SQL command count, logical reads and BenchmarkDotNet/p95

⏱ 30-second answer

The most severe problem is that GetAll() returns IEnumerable<Order>, so every Where after it runs in LINQ to Objects: the whole Orders table is loaded into memory per request. Next is N+1: a query per order for lines plus lazy-loaded Customer, hundreds of round trips. Then CreatedAt.Year == y && CreatedAt.Month == m becomes DATEPART, which is non-SARGable and forces a scan. Next, Include(Attachments) with tracking drags blobs and change-tracking snapshots into a read-only list. Last are sync I/O and missing indexes on the filter columns. The rewrite is one projected, no-tracking, paged query to a DTO with a half-open date range, plus indexes that match it. I prove it with the SQL command count, logical reads and p95. The trade-off is giving up a generic repository for purpose-built queries.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank by impact on production. The worst issue is GetAll() returning IEnumerable<Order>. The moment you call Where on that, you're in LINQ to Objects, so EF runs SELECT * FROM Orders and filters in memory. It works on a dev database with 200 rows and falls over with 5 million. Second is the N+1: the loop runs a query per order for lines, and each o.Customer access lazy-loads another. A customer with 300 orders means 600 round trips. Third, CreatedAt.Year == year && CreatedAt.Month == month translates to DATEPART, which can't seek, so even a correct index gets scanned.

Then the over-fetching: Include(o => o.Attachments) pulls every PDF blob for a list screen, and because it's tracked, EF snapshots all of it too. Then sync ToList() on a request thread, which ties up ThreadPool threads under load. I'd also check indexes against the actual predicates: a unique index on Customers.Number and Orders(CustomerId, CreatedAt) with the list columns included. For example, at [company] a review like this on [the order-history API] took it from [~700] SQL commands and [3.2 s] p95 to [1] command and [60 ms], with logical reads down from [400,000] to [350].

I close with what's blocking: the IEnumerable leak and N+1 must change. Index and async changes are blocking if this endpoint is hot. The repository design is a suggestion, with a conversation about purpose-built query methods. The senior point is that most of these bugs come from one design choice, a generic repository hiding IQueryable, so I'd fix the pattern, not just the method."


Code under review

public class OrderRepository(ShopDbContext db)
{
    public IEnumerable<Order> GetAll() => db.Orders;                                   // 1

    public List<OrderDto> GetForCustomer(string customerNumber, int year, int month)
    {
        var orders = GetAll()
            .Where(o => o.Customer.Number == customerNumber)                         // 1, 2 (lazy Customer)
            .Where(o => o.CreatedAt.Year == year && o.CreatedAt.Month == month)      // 3
            .ToList();                                                               // 6 sync

        var result = new List<OrderDto>();
        foreach (var o in orders)
        {
            var lines = db.OrderLines.Where(l => l.OrderId == o.Id).ToList();        // 2 N+1
            result.Add(new OrderDto(o.Id, o.CreatedAt, o.Customer.Name,              // 2 lazy load
                lines.Sum(l => l.Quantity * l.UnitPrice)));
        }
        return result;
    }

    public List<Order> Search(int year, int month) =>
        db.Orders.Include(o => o.Attachments)                                        // 4 blobs + tracking
                 .Where(o => o.CreatedAt.Year == year && o.CreatedAt.Month == month) // 3
                 .ToList();                                                          // 6
}

Findings, ranked by severity

# Severity Finding Effect in production
1 Stall / outage IEnumerable return makes all filters client-side Full table read per request; memory spikes, timeouts
2 Stall N+1 per order + lazy-loaded Customer Hundreds of round trips; connection pool pressure
3 Slow Year/Month → DATEPART, non-SARGable Index scan instead of seek
4 Slow / memory Include(Attachments) + tracking on a read-only list MBs of blobs per request, LOH allocations, snapshot cost
5 Slow No index for Customers.Number / Orders(CustomerId, CreatedAt) Scans and key lookups
6 Throughput Sync ToList() on request threads, no CancellationToken ThreadPool starvation under load; abandoned requests keep running
7 Design Generic repository returning entities, no paging The same bugs reappear in every new method

The rewrite

One projected, no-tracking, paged query with a half-open date range: see the code example. SQL Server gets one statement that seeks on IX_Orders_CustomerId_CreatedAt and aggregates lines in a correlated subquery.

How I'd close the review

  • Blocking: 1, 2, 3, 6 on this endpoint; 4 for list screens.
  • Blocking with DBA input: 5, with the plan attached showing the seek.
  • Suggested: replace the generic repository with query methods returning DTOs; disable lazy loading proxies.
  • Guardrails: an integration test asserting SQL command count per request, and a PR checklist item for "does this return IQueryable/IEnumerable from the data layer?"

Production example

After the rewrite, the [order-history] endpoint went from [700] commands and [3.2 s] p95 to [1] command and [60 ms]. Its allocation per request fell from [48 MB] to [90 KB] in dotnet-counters, and Gen 2 GCs on the service dropped by [80%].

🔍 What the interviewer is checking

Checks whether the candidate can spot the classic EF Core and SQL performance anti-patterns in real code, rank them by production impact, and propose a measured rewrite and guardrails.

Green flags

  • Spots the IEnumerable client-side evaluation as the top issue and explains why the compiler doesn't catch it
  • Explains N+1 with lazy loading, non-SARGable date parts, and blob over-fetching with tracking
  • Rewrites as one projected, paged, async query with matching indexes
  • Adds guardrails: command-count tests, lazy loading off, PR checklist

Red flags

  • Only suggests "add AsNoTracking" or "add an index"
  • Fixes N+1 by Include-ing everything
  • No ranking or no way to prove the improvement

📚 Learn in depth

1. IEnumerable vs IQueryable is a boundary

db.Orders (IQueryable<Order>)  ── .Where(...) ──► expression tree ──► SQL WHERE
     │
     └─ returned as IEnumerable<Order> ── .Where(...) ──► Enumerable.Where (delegate) ──► runs in memory

Extension method resolution is static. On an IEnumerable<T> variable, Where binds to Enumerable.Where and takes a Func<T,bool>, so EF only ever sees SELECT ... FROM Orders. The compiler gives no warning.

2. N+1 and lazy loading

With lazy loading proxies, accessing o.Customer on an unloaded navigation runs a query. In a loop over N orders, that is N extra round trips, plus N for the explicit line queries. At about 1 ms RTT plus execution time, 600 round trips is easily over a second. Each one also borrows a pooled connection.

3. SARGability of date parts

o.CreatedAt.Year == 2026 translates to DATEPART(year, [o].[CreatedAt]) = @year. SQL Server can't use a B-tree seek on an expression over a column, so it scans. The fix is a half-open range: CreatedAt >= @start AND CreatedAt < @end, where @end is the first instant of the next month. That seeks, and it is correct for datetime2 precision (unlike BETWEEN ... 23:59:59).

4. Over-fetching and tracking

Include of a collection joins in every child row, and with blob columns that means megabytes of data per order. Tracking stores a snapshot of original values for each entity so DetectChanges can compare them later. For a read-only list, projection to a DTO avoids both, and SQL only selects the listed columns, which makes a covering index possible.

5. Indexes that match the query

For the rewritten query:

  • Customers(Number) unique: a seek to one customer.
  • Orders(CustomerId, CreatedAt DESC) INCLUDE (Status): a seek on the customer plus range, ordered for paging, no key lookups.
  • EF Core creates indexes on foreign keys by convention, so OrderLines(OrderId) usually exists already. Check it rather than duplicating it.

6. Sync I/O

Sync ToList() blocks the ThreadPool thread for the whole database call. Under load the pool injects threads slowly, so queues build up and latency climbs even when CPU is low. ToListAsync(ct) frees the thread, and the token stops the query when the client disconnects.

Try it yourself

  1. Log SQL for the original GetForCustomer and count the commands for a customer with 100 orders.
  2. Change GetAll() to return IQueryable<Order> and confirm the WHERE appears in SQL.
  3. Compare the plans for DATEPART(year, CreatedAt) = 2026 and the half-open range with SET STATISTICS IO ON.
  4. Benchmark the original and the rewrite with BenchmarkDotNet ([MemoryDiagnoser]) against a seeded SQL Server container.
  5. Write an EF Core DbCommandInterceptor that counts commands and assert <= 2 in an integration test.

💻 Code

The rewrite: one projected, no-tracking, paged query, a half-open range, async with cancellation, and indexes that match.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;

public sealed record OrderListItem(int Id, DateTime CreatedAt, string CustomerName, string Status, decimal Total);

public sealed class OrderQueries(ShopDbContext db)
{
    public Task<List<OrderListItem>> ForCustomerMonth(
        string customerNumber, int year, int month, int page, int pageSize, CancellationToken ct)
    {
        var start = new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Utc);
        var end = start.AddMonths(1);                                   // half-open range: SARGable and precise

        return db.Orders
            .TagWith("OrderQueries.ForCustomerMonth")
            .Where(o => o.Customer.Number == customerNumber             // join, not lazy load
                     && o.CreatedAt >= start && o.CreatedAt < end)
            .OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id)
            .Skip((page - 1) * pageSize).Take(pageSize)                 // bounded result
            .Select(o => new OrderListItem(                              // projection: no tracking, no blobs
                o.Id, o.CreatedAt, o.Customer.Name, o.Status,
                o.Lines.Sum(l => l.Quantity * l.UnitPrice)))             // aggregated in SQL, no N+1
            .ToListAsync(ct);
    }
}

// Model configuration: indexes that match the predicates and the projected columns.
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Order> b) =>
        b.HasIndex(o => new { o.CustomerId, o.CreatedAt })
         .IsDescending(false, true)
         .IncludeProperties(o => o.Status);   // SQL Server-specific: covering index, no key lookups
}

A guardrail test that fails if the endpoint starts issuing more SQL commands:

public sealed class CommandCounter : Microsoft.EntityFrameworkCore.Diagnostics.DbCommandInterceptor
{
    public int Count;
    public override ValueTask<System.Data.Common.DbDataReader> ReaderExecutedAsync(
        System.Data.Common.DbCommand command, Microsoft.EntityFrameworkCore.Diagnostics.CommandExecutedEventData eventData,
        System.Data.Common.DbDataReader result, CancellationToken cancellationToken = default)
    {
        Interlocked.Increment(ref Count);
        return ValueTask.FromResult(result);
    }
}
// In the integration test (SQL Server in Testcontainers): call the endpoint, then Assert.True(counter.Count <= 1);

⚠ Common mistakes

  • Mistake: Optimising without measuring, for example approving or rejecting the fix on intuition. Why it is wrong: You can't show the gain or catch a regression later. Instead: Attach before/after SQL command counts, logical reads and a BenchmarkDotNet or p95 comparison to the PR.
  • Mistake: Micro-optimising cold paths in the review, such as nitpicking string formatting in an admin export, while missing the N+1 on the hot endpoint. Why it is wrong: Review time goes where users feel nothing. Instead: Rank findings by severity and traffic.
  • Mistake: Returning IEnumerable<T> from a data-access method "for abstraction". Why it is wrong: Every later operator runs in memory after a full table read. Instead: Return materialised DTOs from purpose-built query methods, or keep IQueryable inside the data layer.
  • Mistake: Fixing N+1 by adding Include for everything. Why it is wrong: Multiple collection Includes cause cartesian explosion and still over-fetch. Instead: Project only what the screen needs; use AsSplitQuery when you really need entity graphs.
  • Mistake: Filtering dates with .Year/.Month or .Date and BETWEEN ... 23:59:59. Why it is wrong: Functions on columns block seeks or get poor estimates, and BETWEEN misses fractional seconds with datetime2. Instead: Use >= start AND < nextStart.
  • Mistake: Adding indexes from the review without checking existing ones. Why it is wrong: EF already creates FK indexes, and duplicates add write cost. Instead: Check sys.indexes and the actual plan, and agree with the DBA.
  • Mistake: Leaving lazy loading proxies on globally. Why it is wrong: N+1 bugs hide in any property access, including during JSON serialisation. Instead: Turn lazy loading off and load data explicitly.

🏛 Senior insight: trade-offs

Most of these findings come from one design decision: a generic repository that hides IQueryable behind IEnumerable and returns entities. Fixing each method treats symptoms. There are two honest alternatives. One is to keep IQueryable inside the data layer so filters, projection and paging compose into one SQL statement, but never let it escape to controllers, where anyone can add an N+1 or an untranslatable call. The other is purpose-built query methods (or query handlers) that return materialised DTOs. I prefer the second for APIs, with lazy loading off and a command-count test as a guardrail. Then the next developer can't reintroduce the same bugs without a failing test.

Approach When it fits Cost When not to
Purpose-built query methods returning DTOs Read endpoints, list screens More methods, less reuse Complex domain writes (use aggregates)
Generic repository over IQueryable Small apps, internal tools Leaky abstraction, N+1 risk Performance-sensitive APIs
Include graphs + AsSplitQuery Loading an aggregate to change it Multiple round trips Read-only lists
Raw SQL / SqlQuery<T> Complex reporting SQL Second style Simple lists EF projects well

In the review I attach evidence: the logged SQL before and after, the actual plan showing a seek, and the command-count test. Performance comments with numbers get accepted; opinions get debated.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions client evaluation or over-fetching Why: Checks depth on projection, client evaluation and keeping blobs out of hot queries.
    How to answer

    Over-fetching is loading more than the use case needs: whole entities when the screen uses three columns, or rows you then filter away in memory. Client evaluation makes it worse: everything after AsEnumerable() or ToList() runs in .NET, so a Where or OrderBy placed after it downloads the whole set first. Since EF Core 3, untranslatable expressions throw instead of silently running on the client, except in the final Select, but an explicit AsEnumerable() still moves the work to memory. I fix it by projecting with Select into a DTO, keeping large nvarchar(max) or varbinary(max) columns out of list queries (projection, table splitting or a separate table), and keeping every filter before materialisation. I find it with ToQueryString() and logs. The trade-off: projections mean more DTO types, but each query moves only the data it uses.

  2. When: Candidate mentions the Year/Month predicate preventing a seek Why: Checks they can rewrite other non-SARGable predicates.
    How to answer

    A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.

    • YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.
    • Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.
    • An implicit conversion of the column (e.g. varchar column vs nvarchar parameter) often scans; match types.
    • LIKE 'abc%' seeks; LIKE '%abc' cannot.
    • ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.

    When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.

  3. When: Candidate suggests Include to fix the N+1 Why: Checks they know cartesian explosion and when to use split queries or projection.
    How to answer

    With a single query, each collection Include becomes a LEFT JOIN, and sibling collections multiply: 50 orders x 20 lines x 10 notes x 30 status events is 300,000 rows, with the order's columns repeated on every one. That is cartesian explosion: SQL Server, the network and EF Core's materialiser all process far more rows than the result needs. I confirm it by comparing rows returned in the actual execution plan or SET STATISTICS IO with the number of entities, reading the SQL via ToQueryString(), and checking for EF Core's multiple collection Include warning. Then I pick the fix: project only what the screen needs (often aggregates instead of collections), use AsSplitQuery() when I really need the full entities, or load the collections separately. The trade-off: split queries mean more round trips and no consistent snapshot unless you add a transaction.

🛠 Real-world problems: how you handle them

Order-history API degrading as customers' histories grew
Situation
[Subscription retail platform] on ASP.NET Core and Azure SQL; the order-history page was used [~50,000] times a day. Large B2B customers had [thousands] of orders, and their page loads took over [5 s].
Signals
Application Insights p95 of [3.2 s] with [hundreds] of SQL dependencies per request; dotnet-counters showing [high] allocation rate and Gen 2 GCs; occasional connection pool timeout exceptions at peak.
Investigation
The end-to-end transaction view showed `SELECT ... FROM Orders` with no WHERE, followed by per-order queries. Code review traced it to `GetAll()` returning `IEnumerable`, lazy loading and a per-order lines query. The plan for the search method showed a clustered index scan from `DATEPART`. A memory dump analysed with dotnet-dump showed large byte arrays from the Attachments Include.
Resolution
Immediate: hotfixed the two worst methods to project with a half-open date range and pagination. Long-term: replaced the generic repository with query methods returning DTOs, turned off lazy loading proxies, and added an `Orders(CustomerId, CreatedAt DESC) INCLUDE (Status)` index after reviewing the plan. p95 fell to [60 ms] with [1] SQL command per request.
Prevention
Integration tests with a command-counting interceptor; Roslyn analyser or review checklist item for `IEnumerable` returned from the data layer; Application Insights alert on SQL dependencies per request; ADR on data-access style.

How to tell it (STAR)

**S:** At [company], our order-history API slowed down badly for big customers, and peak hours brought connection pool timeouts. **T:** I picked it up in code review and owned the fix. **A:** I traced it to a generic repository returning `IEnumerable`, which loaded the whole Orders table, plus N+1 lazy loading, a `DATEPART` filter and blob Includes. I hotfixed the hot methods with a projected, paged, range-filtered query, then led replacing the repository with DTO query methods, turned off lazy loading, added a matching index, and added a test that counts SQL commands. **R:** p95 went from [3.2 s] to [60 ms], SQL commands per request from [~700] to [1], and the pool timeouts stopped.

More in EF and SQL Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me