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.
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.
"I'd rank by impact on production. The worst issue is
GetAll()returningIEnumerable<Order>. The moment you callWhereon that, you're in LINQ to Objects, so EF runsSELECT * FROM Ordersand 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 eacho.Customeraccess lazy-loads another. A customer with 300 orders means 600 round trips. Third,CreatedAt.Year == year && CreatedAt.Month == monthtranslates toDATEPART, 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 syncToList()on a request thread, which ties up ThreadPool threads under load. I'd also check indexes against the actual predicates: a unique index onCustomers.NumberandOrders(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
IEnumerableleak 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 hidingIQueryable, so I'd fix the pattern, not just the method."
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
}
| # | 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 |
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.
IQueryable/IEnumerable from the data layer?"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%].
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
IEnumerable client-side evaluation as the top issue and explains why the compiler doesn't catch itRed flags
AsNoTracking" or "add an index"Include-ing everythingdb.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.
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.
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).
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.
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.OrderLines(OrderId) usually exists already. Check it rather than duplicating it.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.
GetForCustomer and count the commands for a customer with 100 orders.GetAll() to return IQueryable<Order> and confirm the WHERE appears in SQL.DATEPART(year, CreatedAt) = 2026 and the half-open range with SET STATISTICS IO ON.[MemoryDiagnoser]) against a seeded SQL Server container.DbCommandInterceptor that counts commands and assert <= 2 in an integration test.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);
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.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..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.sys.indexes and the actual plan, and agree with the DBA.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.
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.
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.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.
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.
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.
Last updated 23 Nov 2026.