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.
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.
"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 callsdb.Payments.FirstOrDefault(p => p.OrderId == o.Id), which is a SQL round trip per order, a classic N+1. ThenIncludeon 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 singleSelectprojection. The rewrite ran [one query in ~70 ms].Then the smaller ones.
Count() > 0makes SQL count every matching row;Any()becomesEXISTS, 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, soToLowerbuys nothing. The action uses synchronousToList()andFirstOrDefault(), 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 aCancellationToken, and an integration test that asserts the dashboard runs at most two queries."
[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
}
| # | 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) |
See the code example: one projected, async query with counts and a payment flag computed in SQL.
| 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 |
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].
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
ToList() before Where and the per-row query the top issues.Any() and counts as subqueries.CancellationToken, and a query-count test.Red flags
var usage first.ToLower() and full-table loads.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)
-- (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;
-- 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.
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.
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.
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'\'
DbCommandInterceptor.Count() > 0 with Any() on an IQueryable and compare SQL.LOWER(Name) LIKE 'abc%' and Name LIKE 'abc%' with an index on Name.bombardier and watch threadpool-queue-length in dotnet-counters.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}");
}
IQueryable, how many round trips run and how much data each returns.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.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().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.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 |
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.