Deciding when EF Core should give way to SqlQuery/FromSql, Dapper or stored procedures for performance: the criteria, the evidence needed, the hidden costs and how to keep mixed data access maintainable.
My default is EF Core, and I drop down only with evidence that the generated SQL or EF's overhead is the bottleneck. Before leaving EF, I use its own escape hatches: projection, ExecuteUpdate/ExecuteDelete, FromSql and SqlQuery<T> for unmapped result types. Good reasons to go further are: SQL that LINQ can't express well (window functions, recursive CTEs, table hints, TVPs); bulk loads with SqlBulkCopy; and very hot, simple reads where Dapper saves measurable allocation. Stored procedures fit DBA-owned, set-based logic, but they cost you deployment coupling and harder testing. I prove the gain with BenchmarkDotNet and Query Store before and after. I keep raw SQL read-side, parameterised and in one place, sharing the DbContext's connection and transaction. The trade-off is speed in a few hot spots against two data-access styles to maintain.
"I treat EF Core as the default and raw SQL as a targeted tool, not a style choice. In modern EF Core the per-query overhead compared with Dapper is small, typically tens of microseconds and some extra allocations per query. That only matters on a path running thousands of times a second. What usually makes a query slow is its shape: the joins, the predicates, the plan. So the first question is whether EF can produce the SQL I want. Often it can with a projection, a split query or
ExecuteUpdate. If not, I useFromSqlorSqlQuery<T>and stay inside EF.I go further when there's a clear reason. One is SQL that LINQ expresses badly: window functions for a ranking report, a recursive CTE over a hierarchy, a TVP join, or a hint. Another is bulk loading, where
SqlBulkCopybeatsSaveChangesby an order of magnitude. A third is a very hot, simple read where Dapper's lower allocation shows up in BenchmarkDotNet and in production. For example, at [company] a [pricing lookup] ran [4,000 times a second]. Moving it from a tracked EF query to a projected no-tracking query got most of the gain. Dapper took a further [15%] off allocation, and we kept that because the path justified it.Stored procedures I use for DBA-owned, set-based work, like a nightly reconciliation, and sometimes as a permission boundary. The mistake I see is teams rewriting whole repositories in Dapper 'for performance' without a profile. They lose change tracking and migrations coverage and get mapping drift, often for no measurable gain. Drop down where the measurement says so, and nowhere else."
| Step | Tool | Use when |
|---|---|---|
| 1 | LINQ with projection, AsNoTracking, split queries |
Most read paths |
| 2 | ExecuteUpdate / ExecuteDelete |
Set-based updates and deletes without loading entities |
| 3 | FromSql (composable) / SqlQuery<T> |
SQL LINQ can't express; results map to entities or simple DTOs |
| 4 | Dapper on the DbContext's connection | Very hot reads, multi-mapping, multiple result sets |
| 5 | Stored procedure | DBA-owned set-based logic, permission boundary, multi-statement batches |
| 6 | SqlBulkCopy / TVPs |
Loading or merging large volumes |
| Criterion | Evidence I want |
|---|---|
| EF can't express the SQL | Generated SQL is inefficient or impossible, e.g. a window function or hint |
| Per-call overhead matters | BenchmarkDotNet shows a meaningful difference and the path is hot (calls/s ร saving) |
| Volume | Rows per operation in the tens of thousands or more |
| Ownership | DBAs maintain the logic or need to tune it without a release |
migrationBuilder.Sql).A [monthly statement] job built statements with EF and LINQ to Objects in [40 minutes]. Rewriting the aggregation as one set-based stored procedure using window functions, then streaming the results with Dapper, took it to [3 minutes]. Query Store showed CPU per run fall by [85%]. The interactive endpoints stayed on EF Core.
Checks whether the candidate makes evidence-based data-access decisions and understands what each alternative really costs, rather than holding a tribal view of ORMs.
Green flags
SqlQuery<T>, ExecuteUpdate, FromSql) before leaving EFRed flags
LINQ expression โ query cache lookup โ (first time) translate to SQL
โ execute command โ DbDataReader โ materialise objects
โ (tracking) identity resolution + snapshot
After the first execution, translation is cached, keyed on the expression shape. The remaining overhead is materialisation and, if tracking, the snapshot. Projection to a DTO with no tracking keeps only materialisation, which is close to what Dapper does. Benchmarks in recent EF Core versions put the remaining gap for simple queries at small microseconds and a few hundred bytes per query. So the gap only matters when it is multiplied by a very high call rate.
FromSql($"...") returns entities and is composable: you can add Where, OrderBy and Include on top when the SQL is a plain SELECT.Database.SqlQuery<T>($"...") (EF Core 8+) maps to unmapped types, including scalars and DTOs.Database.ExecuteSql($"...") runs commands.*Raw forms with string concatenation are where injection creeps in.Use the DbContext's connection and current transaction so both see the same data and commit together:
DbContext โโโบ DbConnection โโโ Dapper
โโโ CurrentTransaction.GetDbTransaction() โโโบ passed to Dapper
Dapper caches materialisers per (SQL, type) and writes values straight into properties, with no change tracker.
EXECUTE permission can be granted without table access.SaveChanges batches statements (42 by default on SQL Server, configurable with MaxBatchSize), but each row is still a statement. SqlBulkCopy streams rows through the TDS bulk-load protocol and can be minimally logged. For loading millions of rows it is commonly 10โ50x faster.
SqlQuery<T> and Dapper on the same query against a local SQL Server container. Report mean and allocated.SqlQuery<T>, Dapper) with [MemoryDiagnoser] against SQL Server in Docker.ROW_NUMBER() in SqlQuery<T> and compare its plan and reads with the LINQ version.AddRange + SaveChanges and with SqlBulkCopy; compare time and transaction log growth.Stay inside EF Core where possible, and use Dapper on the same connection and transaction only for a measured hot path.
namespace Shop.Data;
using System.Data;
using Dapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
public sealed record TopProduct(int CategoryId, int ProductId, string Name, decimal Revenue, long Rank);
public sealed record PriceRow(int ProductId, decimal Price);
public sealed class ReportingQueries(ShopDbContext db)
{
// Window function LINQ expresses poorly: SqlQuery<T> keeps us inside EF (EF Core 8+), parameterised by interpolation.
public Task<List<TopProduct>> TopProductsPerCategory(DateOnly from, int top, CancellationToken ct) =>
db.Database.SqlQuery<TopProduct>($"""
SELECT CategoryId, ProductId, Name, Revenue, Rank FROM (
SELECT p.CategoryId, p.Id AS ProductId, p.Name, SUM(l.Quantity * l.UnitPrice) AS Revenue,
ROW_NUMBER() OVER (PARTITION BY p.CategoryId ORDER BY SUM(l.Quantity * l.UnitPrice) DESC) AS Rank
FROM dbo.OrderLines l
JOIN dbo.Orders o ON o.Id = l.OrderId
JOIN dbo.Products p ON p.Id = l.ProductId
WHERE o.CreatedAt >= {from.ToDateTime(TimeOnly.MinValue)}
GROUP BY p.CategoryId, p.Id, p.Name) AS ranked
WHERE Rank <= {top}
""").ToListAsync(ct);
// Hot path (thousands of calls/s), kept only because BenchmarkDotNet and production showed a gain.
public async Task<IReadOnlyList<PriceRow>> Prices(int[] productIds, CancellationToken ct)
{
var connection = db.Database.GetDbConnection();
if (connection.State != ConnectionState.Open)
await db.Database.OpenConnectionAsync(ct); // EF Core tracks and closes connections it opened
var rows = await connection.QueryAsync<PriceRow>(new CommandDefinition(
"SELECT Id AS ProductId, Price FROM dbo.Products WHERE Id IN (SELECT value FROM OPENJSON(@ids))",
new { ids = System.Text.Json.JsonSerializer.Serialize(productIds) },
transaction: db.Database.CurrentTransaction?.GetDbTransaction(), // same transaction as EF
cancellationToken: ct));
return rows.AsList();
}
}
The measurement that justified it (illustrative shape of a BenchmarkDotNet run; record your own numbers):
| Method | Mean | Allocated |
|---------------------- |---------:|----------:|
| EfTracked | [xx] us | [x.x] KB |
| EfProjectedNoTracking | [xx] us | [x.x] KB |
| Dapper | [xx] us | [x.x] KB |
FromSqlRaw and interpolation. Why it is wrong: It brings back SQL injection and pollutes the plan cache. Instead: Use FromSql/SqlQuery/ExecuteSql with interpolation (parameterised), or Dapper parameters.ORDER BY, or building dynamic SQL inside a stored procedure with EXEC(@sql). Why it is wrong: Identifiers can't be parameters, and dynamic SQL inside a procedure is injectable again. Instead: Map user input to an allow-list of known column names, and use sp_executesql with parameters inside procedures.TransactionScope can escalate to a distributed transaction), and you can block yourself. Instead: Use GetDbConnection() and pass CurrentTransaction.GetDbTransaction() (an extension in Microsoft.EntityFrameworkCore.Storage) so both share one local transaction and isolation level.migrationBuilder.Sql or a database project, and test them against SQL Server in Testcontainers.The real decision is not 'EF or Dapper', it's where you accept a second data-access style and how you contain it. I allow raw SQL on the read side (CQRS-style query handlers) and in bulk jobs, behind one class per use case, sharing the DbContext's connection. Writes go through EF Core so invariants, concurrency tokens and auditing stay in one place. That keeps the blast radius small and code review simple.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
EF projection / SqlQuery<T> |
Most reads, including complex SQL | Very low | SQL needs features only ADO.NET exposes |
| Dapper | Measured hot reads, multi-mapping | Second style, manual mapping | Writes on aggregates, cold paths |
| Stored procedure | Set-based batch logic, DBA ownership, permission boundary | Deployment coupling, testing | Business rules that change every sprint |
SqlBulkCopy / TVP |
10k+ rows per operation | Separate code path, no tracking | Small batches SaveChanges handles fine |
How I measure: BenchmarkDotNet for per-call cost, a load test for throughput, and Query Store for CPU and reads per execution. The decision gets recorded in an ADR with those numbers, so the next engineer knows why this query is different.
Use raw SQL for what LINQ can't express well: hints, window functions, full-text search, table-valued functions or stored procedures. FromSql($"... {id}") takes a FormattableString, so every interpolation hole becomes a DbParameter; that is the safe default. FromSqlRaw takes a plain string and is safe only with explicit @p parameters: passing $"...{input}" to it concatenates the value into SQL, which is SQL injection (EF Core 8's EF1002 analyser warns about it). SqlQuery<T> returns scalars or unmapped DTOs, and ExecuteSql runs commands. Identifiers such as sort columns can never be parameters, so whitelist them. A composable SELECT can have LINQ added on top (EF wraps it as a subquery), but EXEC cannot. The trade-off is power and performance versus losing compile-time checking, so keep raw SQL small and tested.
Pick by volume and shape. SaveChanges batches commands (the SQL Server provider defaults to 42 statements per batch) but still runs one statement per row and tracks every entity, so it is fine for thousands of rows, not millions. ExecuteUpdate/ExecuteDelete run one set-based statement with no tracking; for a million rows I chunk by key range so each transaction stays short. For 5 million inserts, SqlBulkCopy streams rows using the bulk-insert protocol, ideally into a staging table, followed by a set-based MERGE or UPDATE ... JOIN. Table-valued parameters suit thousands of rows sent into one statement. Batch size trades round trips against transaction log growth, lock escalation (about 5,000 locks) and Azure SQL log rate limits. I decide by measuring rows per second and log usage on production-sized data.
BenchmarkDotNet turns a method into a properly measured experiment: it builds a separate Release process, does warm-up and pilot runs so tiered JIT has finished, runs many iterations and reports mean, error and standard deviation.
A correct benchmark:
Baseline = true, so you get a Ratio column;[MemoryDiagnoser] for allocated bytes per operation and GC counts;[GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;Then I check that the difference is bigger than the error, on a quiet machine, before believing it. The trade-off: a micro-benchmark proves one method is faster in isolation; it doesn't prove the endpoint is, so I confirm with production numbers.
How to tell it (STAR)
**S:** At [company], our monthly statement job had grown to [40 minutes] and was about to overrun the overnight window. **T:** I owned making it reliable without rewriting the whole data layer. **A:** I profiled first. The job made [250,000] small queries and aggregated in memory, and BenchmarkDotNet showed EF's own overhead wasn't the problem. I batched the reads, then moved the aggregation into one set-based stored procedure with window functions, called through Dapper on the same connection, and recorded the decision in an ADR. **R:** The job went from [40] to [3 minutes], Azure SQL CPU per run dropped [85%], and the rest of the system stayed on EF Core.
Last updated 23 Nov 2026.