A senior EF Core code review of a slow report: loading a whole table with Include and tracking, in-memory grouping instead of SQL aggregation, string concatenation, no streaming, no cancellation or timeout, ranked by severity with a rewrite.
Ranked by severity: (1) unbounded load: Include(o => o.Lines).ToListAsync() over the whole table brings millions of tracked entities into memory, risking OOM and long blocking; (2) aggregation in memory: grouping and summing in LINQ to Objects instead of letting SQL do GROUP BY ... SUM; (3) tracking a read-only report doubles memory; (4) string concatenation in a loop is O(nยฒ) allocations; (5) no CancellationToken, timeout or streaming, so a closed browser keeps the query running. The rewrite filters to the month, projects a GroupBy with Sum so SQL returns one row per group, streams rows with AsAsyncEnumerable into a StreamWriter, honours cancellation, and moves large exports to a background job writing to Blob Storage. The trade-off: SQL aggregation is far cheaper, but very large or complex reports may need a pre-aggregated table or read replica.
"I'd rank findings by what can hurt production first. The worst problem is that it loads the whole Orders table with every line, as tracked entities, on a web request. Today that's [a few hundred thousand rows], next year it's millions; each request allocates hundreds of megabytes, the change tracker doubles it with snapshots, and two people running the report at once can push the pod into an out-of-memory kill. It also holds the connection and a long-running scan against the primary database.
The second finding is that the work belongs in SQL. The method filters by month and groups by product and region in LINQ to Objects after
ToListAsync(). EF Core translatesWhereon a date range andGroupBywithSumandCountinto a singleGROUP BYquery, so SQL Server reads the month's rows using an index and returns one row per group, maybe a few hundred rows instead of millions. That alone takes it from [minutes] to [around a second] in my experience. Then the smaller items: tracking is pointless for a report, and a projection is untracked anyway; building the CSV withcsv += linecopies the whole string on every iteration; and there's no cancellation token or timeout, so if the user closes the tab, the query keeps going.For example, at [company] a report like this [took the API down at month end] when [the finance team ran it in parallel]. I [rewrote it as a SQL aggregation streamed to the response, and moved the full-detail export to a background job writing to Blob Storage]. Memory per run went from [about 1.5 GB] to [under 50 MB]. I'd close the review with the unbounded load and in-memory grouping as blocking, and the rest as suggestions with a checklist item for reports."
[HttpGet("reports/sales")]
public async Task<IActionResult> MonthlySales(int year, int month) // 5: no CancellationToken
{
var orders = await db.Orders.Include(o => o.Lines).ToListAsync(); // 1: whole table + lines, 3: tracked
var rows = orders
.Where(o => o.CreatedAt.Year == year && o.CreatedAt.Month == month) // 2: filter in memory
.SelectMany(o => o.Lines.Select(l => new { o.Region, l.ProductId, l.Quantity, l.UnitPrice }))
.GroupBy(x => new { x.Region, x.ProductId }) // 2: aggregation in memory
.Select(g => new { g.Key.Region, g.Key.ProductId, Units = g.Sum(x => x.Quantity),
Revenue = g.Sum(x => x.Quantity * x.UnitPrice) });
var csv = "Region,ProductId,Units,Revenue\n";
foreach (var r in rows) csv += $"{r.Region},{r.ProductId},{r.Units},{r.Revenue}\n"; // 4: O(n^2) concatenation
return File(Encoding.UTF8.GetBytes(csv), "text/csv", "sales.csv"); // 6: whole file buffered
}
| # | Severity | Finding | Fix |
|---|---|---|---|
| 1 | Crash / stall | Unbounded load of all orders and lines into memory | Filter in SQL to the month; never ToList a whole table |
| 2 | Stall / cost | Filtering and grouping in LINQ to Objects | Where on a date range + GroupBy with Sum in the query |
| 3 | Waste | Tracked entities for a read-only report | Projection (untracked) or AsNoTracking() |
| 4 | Waste | csv += in a loop: O(nยฒ) copying, LOH allocations |
Write to a StreamWriter |
| 5 | Reliability | No CancellationToken, no command timeout, runs on the request path |
Pass ct; set a timeout; long exports become background jobs |
| 6 | Diagnostics / design | Whole file buffered; no query tag; CSV values not escaped | Stream the response; TagWith; escape CSV fields (and guard against formula injection) |
See the code example: a translated aggregation with a sargable month range, streamed with AsAsyncEnumerable into the response body, cancellable, tagged, with CSV escaping.
(CreatedAt) INCLUDE (Region) and on OrderLines (OrderId) INCLUDE (ProductId, Quantity, UnitPrice); consider a read replica (Business Critical read scale-out) for reporting.CancellationToken and have a row or time budget.A month-end sales report [in a system I worked on] built this way took about 4 minutes and 1.5 GB per run on [600,000] orders; three finance users running it together caused an OOM restart. The rewritten version returned [about 900] grouped rows in about 1.2 seconds using under 50 MB.
Checks that the candidate can rank performance and reliability risks in EF Core code, push work to SQL correctly, stream output, and see the architectural question behind reporting.
Green flags
GroupBy shapes translate to SQLAsAsyncEnumerable and honours cancellationRed flags
AsNoTracking() as the main fixSQL Server: scan Orders + OrderLines (all rows, all columns), JOIN, sort by key
-> network: millions of wide rows (order columns repeated per line)
-> EF Core: materialise entities + snapshots for tracking + identity resolution
-> LINQ to Objects: filter 1/36 of it, group, sum
-> string building: copy the growing CSV on every line
Every stage processes data the result doesn't need. The network part alone is large: 1.8 million detail rows at roughly 200 bytes each is about 360 MB over TDS, against a few hundred aggregated rows of perhaps 50 KB. The memory is the dangerous part: entities, snapshots and a CSV string that ends up on the Large Object Heap (over 85,000 bytes), copied once per line.
SELECT [o].[Region], [l].[ProductId],
SUM([l].[Quantity]) AS [Units],
SUM(CAST([l].[Quantity] AS decimal(18,2)) * [l].[UnitPrice]) AS [Revenue]
FROM [Orders] AS [o]
INNER JOIN [OrderLines] AS [l] ON [o].[Id] = [l].[OrderId]
WHERE [o].[CreatedAt] >= @start AND [o].[CreatedAt] < @end
GROUP BY [o].[Region], [l].[ProductId]
-- Report.MonthlySales
EF Core translates GroupBy followed by aggregate operators (Sum, Count, Average, Min, Max) in the projection into SQL GROUP BY. Since EF Core 7, GroupBy as the final operator (returning the groups with their elements) is also supported, but it is not an aggregation: EF Core fetches every detail row ordered by the key and builds the groups on the client, so for a report it moves exactly the data you were trying to avoid. Project keys and aggregates only.
AsAsyncEnumerable() reads rows from the DbDataReader one at a time; writing each to a StreamWriter over Response.Body sends the file as it's produced. Memory stays flat regardless of row count. The trade-off: once the headers are sent you can't change the status code, so validate inputs before starting.
csv += line allocates a new string of the full length each time: for n lines of average length k, total copying is about kยทnยฒ/2 characters. For 100,000 lines that's billions of character copies. StringBuilder grows geometrically; a StreamWriter avoids holding the file at all.
Anything that might take more than a few seconds, or read large data, is better as a job: the request enqueues it (Azure Service Bus, Hangfire, a queue-triggered Function), a worker writes the file to Blob Storage, and the user gets a link. That isolates the API from report load, allows retries and lets you read from a replica: Azure SQL Premium, Business Critical and Hyperscale offer read scale-out, reached with ApplicationIntent=ReadOnly in the connection string, and geo-replicas are another readable option.
An index on Orders (CreatedAt) INCLUDE (Region) lets the month filter seek, and OrderLines (OrderId) INCLUDE (ProductId, Quantity, UnitPrice) covers the join. For very large history, partitioning by month or a columnstore index on the lines table can make aggregations dramatically cheaper; measure with the actual plan.
Escape commas, quotes and newlines; prefix cells starting with =, +, - or @ to avoid spreadsheet formula injection when finance opens the file in Excel.
dotnet-counters monitor System.Runtime (GC heap size, LOH size).ToQueryString() for the grouped query and confirm it contains GROUP BY; then try GroupBy as the final operator and compare the SQL.+=, StringBuilder and StreamWriter for 100,000 lines with BenchmarkDotNet.The rewrite: SQL aggregation over a sargable month range, streamed as CSV with cancellation.
namespace Shop.Reports;
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
public sealed record SalesRow(string Region, int ProductId, int Units, decimal Revenue);
public sealed class SalesReportQuery(ShopDbContext db)
{
public IAsyncEnumerable<SalesRow> Run(int year, int month)
{
var start = new DateTime(year, month, 1);
var end = start.AddMonths(1);
return db.OrderLines
.TagWith("Report.MonthlySales")
.Where(l => l.Order.CreatedAt >= start && l.Order.CreatedAt < end) // sargable range
.GroupBy(l => new { l.Order.Region, l.ProductId })
.Select(g => new SalesRow(
g.Key.Region,
g.Key.ProductId,
g.Sum(l => l.Quantity),
g.Sum(l => l.Quantity * l.UnitPrice))) // aggregated in SQL
.OrderBy(r => r.Region).ThenBy(r => r.ProductId)
.AsAsyncEnumerable(); // untracked projection, streamed
}
}
[ApiController]
[Route("reports")]
public sealed class ReportsController(SalesReportQuery query) : ControllerBase
{
[HttpGet("sales")]
public async Task MonthlySales([FromQuery] int year, [FromQuery] int month, CancellationToken ct)
{
if (month is < 1 or > 12 || year is < 2000 or > 2100)
{
Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
Response.ContentType = "text/csv";
Response.Headers.ContentDisposition = $"attachment; filename=sales-{year}-{month:00}.csv";
await using var writer = new StreamWriter(Response.Body, new UTF8Encoding(false));
await writer.WriteLineAsync("Region,ProductId,Units,Revenue");
await foreach (var r in query.Run(year, month).WithCancellation(ct))
{
await writer.WriteLineAsync(string.Join(',',
Csv(r.Region), r.ProductId.ToString(CultureInfo.InvariantCulture),
r.Units.ToString(CultureInfo.InvariantCulture), r.Revenue.ToString("0.00", CultureInfo.InvariantCulture)));
}
}
// Escape quotes and separators; neutralise spreadsheet formula injection.
private static string Csv(string value)
{
if (value.Length > 0 && "=+-@".Contains(value[0])) value = "'" + value;
return value.AsSpan().IndexOfAny(",\"\n\r") >= 0 ? $"\"{value.Replace("\"", "\"\"")}\"" : value;
}
}
// Program.cs: a sensible command timeout for reporting queries (seconds).
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(
builder.Configuration.GetConnectionString("Shop"), sql => sql.CommandTimeout(60)));
builder.Services.AddScoped<SalesReportQuery>();
ToListAsync() on a whole table before filtering. Why it is wrong: memory and time grow with the table, not the result, until the process runs out of memory. Instead: filter, aggregate and page in the query.GroupBy with aggregate projections, which EF Core translates to GROUP BY.GroupBy as the final operator and summing the groups afterwards. Why it is wrong: since EF Core 7 this runs, but it fetches every detail row ordered by the key and groups on the client, so it is the in-memory version in disguise. Instead: project only keys and aggregates (g.Sum(...), g.Count()) inside the query..Year and .Month. Why it is wrong: non-sargable, so the month filter scans. Instead: a half-open date range.+=. Why it is wrong: quadratic copying and LOH churn. Instead: write to a StreamWriter (or StringBuilder for small output).CancellationToken, set a command timeout, and move big exports to a background job.= enables formula injection in Excel. Instead: escape and neutralise.A report is a set-based question, so the database should answer it; the application's job is to ask precisely and stream the answer. Beyond fixing the code, I'd ask whether reporting belongs on the transactional database at all: at month end, a read replica, a pre-aggregated summary table updated by a job, or a proper analytics store (Fabric, Synapse) may be the right home. That's a conversation with the product owner about freshness versus cost.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| SQL aggregation streamed on request | Results of hundreds to thousands of rows, seconds to run | Index tuning | Long-running or very large detail exports |
| Background job to Blob Storage | Large exports, minutes to run | Queue, worker, notification | Small interactive reports |
Read replica (ApplicationIntent=ReadOnly) |
Heavy reporting on Business Critical or Hyperscale | Slight replication lag | Need read-your-writes consistency |
| Pre-aggregated table or analytics store | Repeated reports over large history | Pipeline to maintain, data freshness | One-off or rarely run reports |
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.
An EF Core IQueryable is a recipe, not data. Each enumeration (foreach, Count(), Any(), ToList()) sends SQL again, so enumerating twice is two round trips, and if rows change in between the two results disagree (a count of 10, then a loop over 11). A query returned from a method runs only when someone enumerates it; if the scope that owned the DbContext has ended and disposed it by then, you get ObjectDisposedException. And while a query is streaming, its DbDataReader holds the connection, so another command on the same context inside the loop fails (unless MARS is on) or is a hidden N+1. The context isn't thread-safe either, so overlapping operations throw.
ToListAsync() buffers: the connection is freed quickly, but memory holds the whole result. AsAsyncEnumerable() with await foreach streams in constant memory but holds the connection for the whole loop.
I materialise once, inside the unit of work, and stream only large, read-only, no-tracking results.
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 month end our [finance API] kept restarting with out-of-memory errors whenever the sales report ran. **T:** I was asked to make the report safe before the next [month-end close]. **A:** dotnet-counters showed the heap passing [1.5 GB] during one run, and a dump was full of tracked orders and lines: the code loaded the whole table, grouped in memory and built the CSV with string concatenation. I rewrote it as a SQL GROUP BY over a sargable date range, streamed the CSV straight to the response with cancellation, and moved full-detail exports to a background job writing to Blob Storage. **R:** The report now runs in about [1.2 seconds] using under [50 MB], month-end restarts stopped, and other endpoints no longer slow down while finance runs it.
Last updated 23 Nov 2026.