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

📚 Interview question

Code review: a customer dashboard API action in EF Core calls ToList() on Customers before Where, checks Count() > 0, Includes every navigation, calls FirstOrDefault against the database inside a loop over orders, and searches with Name.ToLower().Contains(term). What do you flag, in what order, and what does the rewrite look like?

A code review of an EF Core dashboard action: client-side filtering after ToList(), Count() > 0 instead of Any(), over-eager Include, a database FirstOrDefault inside a loop (N+1), non-sargable ToLower() search, tracking and sync calls; ranked by severity with a projected rewrite.

Mid-Level CodeReview Intermediate code-review ef-core include linq n-plus-one query-performance

🎯 Key points

  • ToList() before Where loads the whole table: the most severe issue
  • FirstOrDefault per loop iteration = N+1 round trips; prefetch with one Contains query or project
  • Include on every navigation over-fetches and can cause cartesian explosion
  • Returning entities exposes fields like notes and contacts (APP risk); return DTOs
  • Count() > 0 counts all rows; Any() becomes EXISTS and stops at the first
  • ToLower() on a column is non-sargable; rely on the case-insensitive collation, or EF.Functions.Collate when a specific collation is needed
  • Synchronous calls block threads; use the async APIs and pass the request CancellationToken
  • Close with blocking (must fix before merge) vs suggested comments and a query-count test

⏱ 30-second answer

I'd rank findings by impact. Blocking: ToList() before Where loads every customer into memory; the FirstOrDefault per order is an N+1 (one round trip per row); Include on every navigation over-fetches and multiplies rows; and returning entities exposes notes and contacts, a privacy risk under the Australian Privacy Principles. Should fix: Count() > 0 scans instead of Any() (EXISTS); Name.ToLower().Contains(term) is non-sargable and redundant on a case-insensitive collation; synchronous calls block request threads and ignore cancellation.

The rewrite is one projected query into DTOs: filter in SQL, Select exactly what the dashboard shows (counts and flags as subqueries), async with the request's CancellationToken so abandoned requests stop their SQL. Then a test asserts the endpoint runs a bounded number of queries.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd read it for what reaches the database first, because that's where the damage is. db.Customers.ToList().Where(...) is the worst line: it pulls every customer, every column, into memory and tracks them, then filters in C#. That's a full scan and hundreds of megabytes on a big table. Next is the loop: for each order it calls db.Payments.FirstOrDefault(p => p.OrderId == o.Id), which is a SQL round trip per order, a classic N+1. Then Include on six navigations, including two collections, so EF Core builds a wide join with a row per combination.

For example, at [company] I reviewed [a dashboard action] almost exactly like this. It was fine in test with [200 customers] and took [~9 s] in production with [~300,000]. I left three blocking comments, the filter after ToList(), the N+1 and the Includes, and suggested a single Select projection. The rewrite ran [one query in ~70 ms].

Then the smaller ones. Count() > 0 makes SQL count every matching row; Any() becomes EXISTS, which stops at the first. Name.ToLower().Contains(term) wraps the column in a function, so even a prefix search can't seek an index, and SQL Server's default collation is already case-insensitive, so ToLower buys nothing. The action uses synchronous ToList() and FirstOrDefault(), which hold a thread-pool thread for the whole database call. And it's a read path with tracking on. I'd close the review by asking for a projection, async calls with a CancellationToken, and an integration test that asserts the dashboard runs at most two queries."


Code under review

[HttpGet("dashboard")]
public IActionResult Dashboard(string term)
{
    var customers = db.Customers
        .Include(c => c.Orders).ThenInclude(o => o.Lines)
        .Include(c => c.Addresses)
        .Include(c => c.Contacts)
        .Include(c => c.Notes)
        .ToList()                                                  // 1
        .Where(c => c.Name.ToLower().Contains(term.ToLower()))     // 2
        .ToList();

    var result = new List<object>();
    foreach (var c in customers)
    {
        foreach (var o in c.Orders)
        {
            var payment = db.Payments.FirstOrDefault(p => p.OrderId == o.Id);   // 3
            result.Add(new { c.Name, o.Number, Paid = payment != null });
        }
        if (c.Orders.Count() > 0) { /* show badge */ }             // 4
    }
    return Ok(new { customers, result });                          // 5
}

Findings by severity

# Severity Finding Fix
1 Stall / outage risk ToList() before Where: whole table loaded and tracked Filter on IQueryable before materialising
3 Stall FirstOrDefault against the database per order: N+1 Project o.Payments.Any() in the query, or prefetch with one query
— Stall Six Includes incl. sibling collections: over-fetching, cartesian explosion Project only what the dashboard needs
5 Data exposure Returns entities (with Notes, contacts) to the client Return DTOs
2 Performance ToLower() on a column: non-sargable, redundant with a CI collation c.Name.Contains(term) or StartsWith; full-text for real search
— Throughput Sync ToList/FirstOrDefault block threads ToListAsync(ct)
4 Minor Count() > 0 Any() (here, in-memory, but the habit matters on IQueryable)
— Minor Tracking on a read path Projection (DTOs aren't tracked)

The rewrite

See the code example: one projected, async query with counts and a payment flag computed in SQL.

How I'd close the review

Type Comment
Blocking Filter before materialising; remove the per-order query; project instead of six Includes; don't return entities
Suggested Use Any(); drop ToLower(); async with CancellationToken
Follow-up Integration test asserting ≤ 2 SQL commands; turn MultipleCollectionIncludeWarning into an error in development

Production example

The original action took [~9 s] and allocated [~600 MB] for a search over [~300,000] customers, issuing [~1,500] queries. The projected rewrite issued [1] query, allocated [~2 MB] and returned in [~70 ms].

🔍 What the interviewer is checking

Checks that the candidate can spot EF Core performance and data-exposure problems in real code, rank them by severity and propose a concrete rewrite with a regression guard. ("Blocking" comments are the ones that must be fixed before the pull request can merge; "suggested" ones are improvements the author may defer.)

Green flags

  • Calls ToList() before Where and the per-row query the top issues.
  • Explains the SQL each line produces.
  • Rewrites as a single projected DTO query with Any() and counts as subqueries.
  • Mentions entity exposure, async with CancellationToken, and a query-count test.

Red flags

  • Focuses on naming or var usage first.
  • Fixes the N+1 by adding more Includes.
  • Keeps ToLower() and full-table loads.

📚 Learn in depth

1. Reading a query for its SQL

Ask three questions of every EF Core query in review:

1. Where does it stop being IQueryable?   (ToList, AsEnumerable, foreach, IEnumerable return)
2. How many round trips?                   (loops, lazy loading, repeated enumeration)
3. How much data per round trip?           (Include, wide entities, missing Select)

2. The original's SQL

-- (1) the Include query, no WHERE: every customer × orders × lines × addresses × contacts × notes
SELECT c.*, o.*, l.*, a.*, ct.*, n.*
FROM Customers c
LEFT JOIN Orders o ON ...
LEFT JOIN OrderLines l ON ...
LEFT JOIN Addresses a ON ...
LEFT JOIN Contacts ct ON ...
LEFT JOIN Notes n ON ...
ORDER BY c.Id, o.Id, l.Id, a.Id, ct.Id, n.Id;

-- (3) once per order
SELECT TOP(1) p.* FROM Payments p WHERE p.OrderId = @id;

3. Any() versus Count() > 0

-- Count() > 0 on IQueryable
SELECT COUNT(*) FROM Orders WHERE CustomerId = @c      -- touches every matching row

-- Any()
SELECT CASE WHEN EXISTS (SELECT 1 FROM Orders WHERE CustomerId = @c) THEN 1 ELSE 0 END

On an in-memory List<T>, Count() > 0 is O(1) via ICollection.Count; the habit matters on queries.

4. Sargability and collations

LOWER([c].[Name]) LIKE '%' + @term + '%' evaluates LOWER per row. SQL Server's default collation for new Azure SQL databases (SQL_Latin1_General_CP1_CI_AS) is case-insensitive, so Name LIKE ... already ignores case. Leading % still prevents an index seek; StartsWith (LIKE @term + '%') can seek, and full-text search handles word search properly.

5. Sync over the database

ToList() blocks the request thread while SQL Server works. Under load, blocked threads make the thread pool inject more threads slowly (about one or two per second once past the minimum), so latency spikes look like database slowness but are really thread starvation.

6. The rewrite's SQL

SELECT TOP(@p) [c].[Id], [c].[Name],
  (SELECT COUNT(*) FROM [Orders] AS [o] WHERE [c].[Id] = [o].[CustomerId]),
  [o0].[Number], CASE WHEN EXISTS (SELECT 1 FROM [Payments] AS [p] WHERE [o0].[Id] = [p].[OrderId]) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, ...
FROM [Customers] AS [c]
LEFT JOIN (... recent orders ...) AS [o0] ON ...
WHERE [c].[Name] LIKE @term_contains ESCAPE N'\'

Try it yourself

  1. Run the original against 10,000 seeded customers and count commands with a DbCommandInterceptor.
  2. Replace Count() > 0 with Any() on an IQueryable and compare SQL.
  3. Compare execution plans for LOWER(Name) LIKE 'abc%' and Name LIKE 'abc%' with an index on Name.
  4. Load-test the sync and async versions with a tool like bombardier and watch threadpool-queue-length in dotnet-counters.
  5. Write the integration test that asserts the dashboard runs at most two queries.

💻 Code

The rewrite: filter in SQL, project what the dashboard shows, async with cancellation.

namespace Crm.Api.Dashboard;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public sealed record DashboardOrder(string Number, bool Paid);
public sealed record DashboardCustomer(int Id, string Name, int OrderCount, IReadOnlyList<DashboardOrder> RecentOrders);

[ApiController]
[Route("dashboard")]
public sealed class DashboardController(CrmDbContext db) : ControllerBase
{
    private const int MaxCustomers = 50;

    [HttpGet]
    public async Task<ActionResult<IReadOnlyList<DashboardCustomer>>> Get(
        [FromQuery] string term, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(term) || term.Length < 2)
            return BadRequest("Search term must be at least 2 characters.");

        var customers = await db.Customers
            .Where(c => c.Name.Contains(term))                 // CI collation: no ToLower needed
            .OrderBy(c => c.Name).ThenBy(c => c.Id)
            .Take(MaxCustomers)
            .Select(c => new DashboardCustomer(
                c.Id,
                c.Name,
                c.Orders.Count(),                                // COUNT subquery
                c.Orders
                    .OrderByDescending(o => o.PlacedAt)
                    .Take(5)
                    .Select(o => new DashboardOrder(o.Number, o.Payments.Any()))  // EXISTS, no N+1
                    .ToList()))
            .ToListAsync(ct);                                    // one query, async, untracked DTOs

        return Ok(customers);
    }
}
// Integration test guarding the fix (xUnit + WebApplicationFactory + Testcontainers SQL Server).
[Fact]
public async Task Dashboard_runs_a_bounded_number_of_queries()
{
    var counter = factory.Services.GetRequiredService<CommandCounter>();
    var response = await client.GetAsync("/dashboard?term=smi");

    response.EnsureSuccessStatusCode();
    Assert.True(counter.Count <= 2, $"Expected at most 2 SQL commands, got {counter.Count}");
}

⚠ Common mistakes

  • Mistake: Reviewing EF Core code only as C#. Why it is wrong: the cost is in the SQL and round trips, which the C# hides. Instead: ask where it stops being IQueryable, how many round trips run and how much data each returns.
  • Mistake: Treating ToList() before Where as a style nit. Why it is wrong: it loads the whole table; it's the most severe finding. Instead: mark it blocking.
  • Mistake: Fixing the N+1 by adding Include(o => o.Payments) on top of the other Includes. Why it is wrong: it removes round trips but makes the cartesian product bigger. Instead: project o.Payments.Any().
  • Mistake: Suggesting ToLower() on both sides for case-insensitive search. Why it is wrong: it is non-sargable and redundant with a case-insensitive collation. Instead: rely on the collation, or EF.Functions.Collate when needed.
  • Mistake: Flagging everything with the same weight. Why it is wrong: the author can't tell the outage risk from the nit. Instead: rank by severity and mark blocking versus suggested.
  • Mistake: Approving without a guard against regression. Why it is wrong: the next change can reintroduce an N+1. Instead: request a query-count integration test.
  • Mistake: Missing that entities are returned to the client. Why it is wrong: it exposes fields such as notes and contacts, a privacy risk under the Australian Privacy Principles. Instead: require DTOs.

🏛 Senior insight: trade-offs

A good EF Core review is a SQL review in disguise. I rank findings by what they do in production: full-table loads and N+1 first, data exposure next, then sargability, threading and tidiness. I make the fix measurable: before and after command counts and durations, and a test that keeps it that way.

I also look for the systemic fix: an analyser or architecture test (no ToList() followed by Where on a DbSet, no entities in controller return types), warnings as errors for multiple-collection Includes, and a short EF Core section in the review checklist.

Option When it fits Cost When not to
Single projected query Dashboards, lists DTOs to maintain When the full graph must be modified
Prefetch with one Contains query + dictionary Loops that need related data Two queries, memory for the lookup Very large key sets (batch them)
Split query with Includes Full graph genuinely needed Extra round trips Read-only summaries
Query-count tests Hot endpoints Test infrastructure Rarely used admin screens

🔗 Follow-ups the interviewer may ask

  1. When: Candidate also discusses LINQ to Objects performance in the same code. Why: Checks the general LINQ performance review alongside the EF Core view.
    How to answer

    The big problems are where the work runs and how often it runs. ToList() before Where pulls whole tables into memory, and loading related data inside the foreach is an N+1. A FirstOrDefault on a list inside a loop makes it O(n times m), and enumerating the same query several times repeats the round trips. Smaller fixes are Any() instead of Count() > 0, and MinBy or a SQL TOP 1 instead of OrderBy().First(). A 50,000-id Contains needs batching or a table-valued parameter. My rewrite filters and projects in one SQL query with AsNoTracking, builds a dictionary for lookups, materialises once, and I measure before and after.

  2. When: Candidate mentions the multiple Includes multiplying rows. Why: Checks cartesian explosion and split queries.
    How to answer

    Cartesian explosion happens when one query Includes two or more sibling collections: SQL returns one row per combination, so an order with 50 lines and 20 payments becomes 1,000 rows, each repeating the order's columns. EF Core logs a warning when it sees this.

    AsSplitQuery() makes EF Core send one root query plus one query per collection Include (orders; then lines joined to the same filtered orders; then payments) and stitch the results together in memory. For that order, rows transferred become 1 (root) + 50 (lines) + 20 (payments) = 71 instead of 1,000.

    The trade-offs: an extra round trip per collection (it adds up with network latency), and the statements are not one consistent snapshot unless you wrap them in a transaction with snapshot isolation. Often the better answer is a projection that loads only what's needed.

  3. When: Candidate proposes a DTO projection. Why: Checks the Include versus projection trade-off in depth.
    How to answer

    For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.

    • Navigations used inside Select are joined automatically; no Include is needed (and Include is ignored there).
    • Include is still right when I load an aggregate to modify and save it, because I need tracked entities.

    The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.

🛠 Real-world problems: how you handle them

Customer dashboard took 9 seconds in production after passing review in test
Situation
A [CRM] web API on Azure SQL in Australia East had a new customer dashboard endpoint used by [~400] sales staff. Test data had [~200] customers; production had [~300,000].
Signals
p95 for `GET /dashboard` at [~9 s] on day one; App Service memory alerts at [~85%]; Application Insights showed [~1,500] SQL dependencies for some requests; Azure SQL CPU spikes during business hours.
Investigation
Opened slow requests in Application Insights: one huge first query, then hundreds of `SELECT TOP(1) ... FROM Payments`. Captured the first query with `ToQueryString()`: no `WHERE`, six joins. dotnet-counters showed GC heap growth to [~1.5 GB] and rising thread-pool queue length from synchronous calls.
Resolution
Immediate: hotfix moved the `Where` before `ToList()` and capped results at 50, cutting load sharply. Real fix: rewrote the action as one projected, async query with counts and payment flags as subqueries, returning DTOs instead of entities.
Prevention
Query-count integration tests for dashboard endpoints; an architecture test banning entity types in controller return values; `MultipleCollectionIncludeWarning` set to throw in development; performance tests seeded with production-like volumes; EF Core section added to the PR checklist.

How to tell it (STAR)

**S:** At [company], a new CRM dashboard passed review and testing but took [9 seconds] on its first day in production. **T:** I was asked to [fix it fast and work out why review missed it]. **A:** Application Insights showed a full-table query followed by hundreds of per-order payment lookups. I shipped a hotfix that filtered before materialising, then rewrote the action as one projected async query returning DTOs. I added a query-count test and a checklist item for loading data before filtering and for N+1 patterns, and seeded the performance environment with realistic volumes. **R:** p95 dropped to [~70 ms], memory alerts stopped, and the query-count test has since blocked [two] regressions before merge.

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me