Making slow EF Core queries fast

Three Entity Framework Core performance problems, rebuilt from scratch on a generated trucking dataset and measured with BenchmarkDotNet against a local PostgreSQL. Each one comes down to asking the database for more than the code needs.

Reading too much: the Cartesian explosion

A carrier profile needs the carrier, its inspections with their violations, its crashes, vehicles and drivers. Chaining Include calls gets all of it in one query, but those collections are siblings: the SQL joins them side by side, so every inspection row repeats for every crash, every vehicle and every driver. No table is big; six of them multiplied are.

For one carrier with 50 inspections with 4 violations each, 10 crashes, 25 vehicles and 20 drivers, that one query read 1,000,000 rows and took 7,151 ms.

See the rows multiply

Change the carrier’s record and watch what each strategy reads back. The counts use the same formulas the benchmark’s measured row counts are tested against.

50
4
10
25
20

Single query

Every Include joined into one result

1,000,000 rows1 query

Split query

One query per collection

306 rows6 queries

Projection

Only the numbers the page shows

1 row1 query

1 dot = 1,667 rowsRows the page needsThe same data, repeated by the join

AsSplitQuery() sends one query per collection instead: same C#, one line different, and 306 rows in 1.69 ms.

Before: one query

Rows read
1,000,000
Queries
1
Mean time
7,151 ms
var carrier = await db.Carriers
    .AsNoTracking()
    .Include(c => c.Inspections)
        .ThenInclude(i => i.Violations)
    .Include(c => c.Crashes)
    .Include(c => c.Vehicles)
    .Include(c => c.Drivers)
    .AsSingleQuery()
    .SingleAsync(c => c.DotNumber == dotNumber);
SQL EF sent (1 statement)
SELECT c1.id, c1.city, c1.dot_number, c1.driver_count, c1.legal_name, c1.power_units, c1.state, s.id, s.carrier_id, s.date, s.level, s.out_of_service, s.state, s.id0, s.code, s.description, s.inspection_id, s.out_of_service0, s.severity, c0.id, c0.carrier_id, c0.date, c0.fatalities, c0.injuries, c0.state, c0.tow_away, v0.id, v0.carrier_id, v0.kind, v0.model_year, v0.unit_number, d.id, d.carrier_id, d.has_cdl, d.hired_on, d.license_state
FROM (
    SELECT c.id, c.city, c.dot_number, c.driver_count, c.legal_name, c.power_units, c.state
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    LIMIT 2
) AS c1
LEFT JOIN (
    SELECT i.id, i.carrier_id, i.date, i.level, i.out_of_service, i.state, v.id AS id0, v.code, v.description, v.inspection_id, v.out_of_service AS out_of_service0, v.severity
    FROM inspections AS i
    LEFT JOIN violations AS v ON i.id = v.inspection_id
) AS s ON c1.id = s.carrier_id
LEFT JOIN crashes AS c0 ON c1.id = c0.carrier_id
LEFT JOIN vehicles AS v0 ON c1.id = v0.carrier_id
LEFT JOIN drivers AS d ON c1.id = d.carrier_id
ORDER BY c1.id, s.id, s.id0, c0.id, v0.id

After: split query

Rows read
306
Queries
6
Mean time
1.69 ms
var carrier = await db.Carriers
    .AsNoTracking()
    .Include(c => c.Inspections)
        .ThenInclude(i => i.Violations)
    .Include(c => c.Crashes)
    .Include(c => c.Vehicles)
    .Include(c => c.Drivers)
    .AsSplitQuery()
    .SingleAsync(c => c.DotNumber == dotNumber);
SQL EF sent (6 statements)
SELECT c.id, c.city, c.dot_number, c.driver_count, c.legal_name, c.power_units, c.state
FROM carriers AS c
WHERE c.dot_number = @dotNumber
ORDER BY c.id
LIMIT 2
SELECT i.id, i.carrier_id, i.date, i.level, i.out_of_service, i.state, c1.id
FROM (
    SELECT c.id
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    ORDER BY c.id
    LIMIT 1
) AS c1
INNER JOIN inspections AS i ON c1.id = i.carrier_id
ORDER BY c1.id, i.id
SELECT v.id, v.code, v.description, v.inspection_id, v.out_of_service, v.severity, c1.id, i.id
FROM (
    SELECT c.id
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    ORDER BY c.id
    LIMIT 1
) AS c1
INNER JOIN inspections AS i ON c1.id = i.carrier_id
INNER JOIN violations AS v ON i.id = v.inspection_id
ORDER BY c1.id, i.id
SELECT c0.id, c0.carrier_id, c0.date, c0.fatalities, c0.injuries, c0.state, c0.tow_away, c2.id
FROM (
    SELECT c.id
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    ORDER BY c.id
    LIMIT 1
) AS c2
INNER JOIN crashes AS c0 ON c2.id = c0.carrier_id
ORDER BY c2.id
SELECT v0.id, v0.carrier_id, v0.kind, v0.model_year, v0.unit_number, c3.id
FROM (
    SELECT c.id
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    ORDER BY c.id
    LIMIT 1
) AS c3
INNER JOIN vehicles AS v0 ON c3.id = v0.carrier_id
ORDER BY c3.id
SELECT d.id, d.carrier_id, d.has_cdl, d.hired_on, d.license_state, c4.id
FROM (
    SELECT c.id
    FROM carriers AS c
    WHERE c.dot_number = @dotNumber
    ORDER BY c.id
    LIMIT 1
) AS c4
INNER JOIN drivers AS d ON c4.id = d.carrier_id
ORDER BY c4.id

If the page only shows counts and totals, ask for those directly. A Select projection lets PostgreSQL do the counting and sends back one row.

Better: projection

Rows read
1
Queries
1
Mean time
0.71 ms
var summary = await db.Carriers
    .Where(c => c.DotNumber == dotNumber)
    .Select(c => new CarrierSummary(
        c.DotNumber,
        c.LegalName,
        c.Inspections.Count(),
        c.Inspections.Count(i => i.OutOfService),
        c.Inspections.SelectMany(i => i.Violations).Count(),
        c.Crashes.Count(),
        c.Crashes.Sum(x => x.Fatalities),
        c.Crashes.Sum(x => x.Injuries),
        c.Vehicles.Count(),
        c.Drivers.Count()))
    .SingleAsync();
SQL EF sent (1 statement)
SELECT c.dot_number, c.legal_name, (
    SELECT count(*)::int
    FROM inspections AS i
    WHERE c.id = i.carrier_id), (
    SELECT count(*)::int
    FROM inspections AS i0
    WHERE c.id = i0.carrier_id AND i0.out_of_service), (
    SELECT count(*)::int
    FROM inspections AS i1
    INNER JOIN violations AS v ON i1.id = v.inspection_id
    WHERE c.id = i1.carrier_id), (
    SELECT count(*)::int
    FROM crashes AS c0
    WHERE c.id = c0.carrier_id), (
    SELECT COALESCE(sum(c1.fatalities), 0)::int
    FROM crashes AS c1
    WHERE c.id = c1.carrier_id), (
    SELECT COALESCE(sum(c2.injuries), 0)::int
    FROM crashes AS c2
    WHERE c.id = c2.carrier_id), (
    SELECT count(*)::int
    FROM vehicles AS v0
    WHERE c.id = v0.carrier_id), (
    SELECT count(*)::int
    FROM drivers AS d
    WHERE c.id = d.carrier_id)
FROM carriers AS c
WHERE c.dot_number = @dotNumber
LIMIT 2

A projection reads only what the code needs. That matters even more when the read is there to feed a save.

Full numbers (reading too much)

Saving too much: read to decide, write to save

Deciding a carrier’s funding application takes facts from its safety record and from 100,000 invoices with 4 lines each. The save itself changes one row and adds one note.

Loading all of that tracked means SaveChanges has to compare every loaded entity to find the one that changed. Asking the database for just the facts, then writing the one row, skips both the load and the comparison.

Before: load everything, tracked

Mean time
6,266 ms
Tracked at save
500,303
Rows read
500,301
Write commands
1
var application = await db.FundingApplications
    .Include(a => a.Carrier).ThenInclude(c => c.Inspections).ThenInclude(i => i.Violations)
    .Include(a => a.Carrier).ThenInclude(c => c.Crashes)
    .Include(a => a.Invoices).ThenInclude(i => i.Lines)
    .Include(a => a.Documents)
    .AsSplitQuery()
    .SingleAsync(a => a.Id == applicationId); // every row is now tracked

var decision = DecisionRules.Decide(DecisionFacts.FromGraph(application, Seeder.Today));
application.Status = decision.Status;
application.DecidedAt = now;
db.DecisionNotes.Add(new DecisionNote
{
    FundingApplicationId = applicationId,
    Text = decision.Reason,
    CreatedAt = now,
});
await db.SaveChangesAsync(); // DetectChanges compares every tracked entity

After: project, then ExecuteUpdate

Mean time
500 ms
Tracked at save
1
Rows read
1
Write commands
2
var facts = await DecisionFacts
    .Project(db.FundingApplications.Where(a => a.Id == applicationId), Seeder.Today)
    .SingleAsync();
var decision = DecisionRules.Decide(facts);

// ExecuteUpdate commits on its own, so keep it and the note in one transaction.
await using var transaction = await db.Database.BeginTransactionAsync();
await db.FundingApplications
    .Where(a => a.Id == applicationId)
    .ExecuteUpdateAsync(s => s
        .SetProperty(a => a.Status, decision.Status)
        .SetProperty(a => a.DecidedAt, now)); // one UPDATE, nothing tracked
db.DecisionNotes.Add(new DecisionNote
{
    FundingApplicationId = applicationId,
    Text = decision.Reason,
    CreatedAt = now,
});
await db.SaveChangesAsync();
await transaction.CommitAsync();
The projection it uses
applications.Select(a => new DecisionFacts(
    a.Carrier.Inspections.Count(),
    a.Carrier.Inspections.Count(i => i.OutOfService),
    a.Carrier.Inspections.SelectMany(i => i.Violations).Count(v => v.Severity >= SevereFrom),
    a.Carrier.Crashes.Count(c => c.Fatalities > 0),
    a.Invoices.Where(i => !i.Paid).Sum(i => i.Amount),
    a.Invoices.Count(),
    a.Invoices.Count(i => !i.Paid && i.DueOn < today),
    a.Invoices.Count(i => i.Amount != i.Lines.Sum(l => l.Amount)),
    a.Documents.Any(d => d.Kind == "Insurance" && d.ExpiresOn >= today),
    a.RequestedAmount));

That 6,266 ms covers loading and tracking 500,303 entities as well as the save’s comparison; the benchmark doesn’t time them separately. The narrow versions skip both.

From 10,000 to 100,000 invoices, loading everything tracked went from 274 ms and 101 MB to 6,266 ms and 977 MB. The projection-based saves went from 42.2 ms to 500 ms and stayed around 109 KB.

ExecuteUpdate goes straight to the database: entity interceptors, concurrency-token checks and domain events don’t run for that update.

When you still need the change tracker

Mean time
504 ms
Tracked at save
2
Rows read
2
Write commands
1
var facts = await DecisionFacts
    .Project(db.FundingApplications.Where(a => a.Id == applicationId), Seeder.Today)
    .SingleAsync();
var decision = DecisionRules.Decide(facts);

var application = await db.FundingApplications.FindAsync(applicationId); // one tracked row
application!.Status = decision.Status;
application.DecidedAt = now;
db.DecisionNotes.Add(new DecisionNote
{
    FundingApplicationId = applicationId,
    Text = decision.Reason,
    CreatedAt = now,
});
await db.SaveChangesAsync();

Project the facts, then load only the row you change. The tracker still sees the update, so its checks and events run, but it has two entities to compare instead of tens of thousands.

Narrow queries still add up when every service in a request fetches the same carrier again.

Full numbers (saving too much)

Connecting too much: DbContext lifetimes

A request runs through five services that all need the same carrier, and each looks it up with FindAsync. Find checks the context’s change tracker before going to the database, so it only helps if the services share a context.

Register the context as transient and every service gets its own: 5 queries and 5 connection checkouts per request. Scoped shares one context for the request, and pooling also reuses context instances between requests.

Npgsql pools connections, so a checkout usually reuses an open connection rather than creating one. Each extra checkout is still a round trip and more traffic through the pool.

Transient

A new context for every service

1.10 ms per request

5 queries, 5 connection checkouts

services.AddDbContext<FleetDbContext>(UsePostgres, ServiceLifetime.Transient);

Scoped

One context per request, shared

0.25 ms per request

1 query, 1 connection checkout

services.AddDbContext<FleetDbContext>(UsePostgres); // scoped is the default

Pooled

Scoped, reusing context instances

0.17 ms per request

1 query, 1 connection checkout

services.AddDbContextPool<FleetDbContext>(UsePostgres);

Full numbers (connecting too much)

Results

Loading one carrier

Loading one carrier: mean time per load
CarrierStrategyMean ± std devAllocatedQueriesRows read
10 inspections × 3 violations, 4 crashes, 5 vehicles, 5 driversSingle query18.8 ms ± 0.65 ms5,396 KB13,000
10 inspections × 3 violations, 4 crashes, 5 vehicles, 5 driversSplit query1.40 ms ± 0.12 ms149 KB655
10 inspections × 3 violations, 4 crashes, 5 vehicles, 5 driversProjection0.65 ms ± 0.06 ms61 KB11
50 inspections × 4 violations, 10 crashes, 25 vehicles, 20 driversSingle query7,151 ms ± 93.4 ms1,765,894 KB11,000,000
50 inspections × 4 violations, 10 crashes, 25 vehicles, 20 driversSplit query1.69 ms ± 0.09 ms388 KB6306
50 inspections × 4 violations, 10 crashes, 25 vehicles, 20 driversProjection0.71 ms ± 0.07 ms61 KB11

Back to the section (Loading one carrier)

Deciding and saving one application

Each application has 4 lines per invoice and 40 documents, on the large carrier above.

Deciding and saving one application: mean time per save
ApplicationStrategyMean ± std devAllocatedRead commandsRows readTracked at saveWrite commands
10,000 invoicesLoad everything, tracked274 ms ± 21.9 ms103,381 KB750,30150,3031
10,000 invoicesProjection, then one tracked row43.4 ms ± 5.20 ms113 KB2221
10,000 invoicesProjection, then ExecuteUpdate42.2 ms ± 7.30 ms107 KB1112
100,000 invoicesLoad everything, tracked6,266 ms ± 71.8 ms1,000,119 KB7500,301500,3031
100,000 invoicesProjection, then one tracked row504 ms ± 18.1 ms115 KB2221
100,000 invoicesProjection, then ExecuteUpdate500 ms ± 24.3 ms109 KB1112

Back to the section (Deciding and saving one application)

One request through five services

One request through five services: mean time per request
DbContext lifetimeMean ± std dev per requestAllocatedQueriesConnection checkouts
Transient1.10 ms ± 0.01 ms308 KB55
Scoped0.25 ms ± 0.00 ms75 KB11
Pooled0.17 ms ± 0.01 ms16 KB11

Back to the section (One request through five services)

Measured December 4, 2026 with BenchmarkDotNet on Microsoft Windows 10.0.26300, 13th Gen Intel(R) Core(TM) i9-13900K (32 logical cores), .NET 10.0.15, EF Core 10.0.15, Npgsql 10.0.4 and a local PostgreSQL 18.7.

Generated, deterministic dataset (seed 20261204, 502 carriers); not real carrier records. Every number on this page comes from one run of the benchmark; none are edited by hand.