📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

When would you drop down from EF Core to Dapper, raw SQL or a stored procedure for performance? What criteria do you use, how do you measure whether it is worth it, and how do you keep the codebase consistent when you do?

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.

Senior Architecture Advanced architecture dapper ef-core performance raw-sql stored-procedures

๐ŸŽฏ Key points

  • Default to EF Core; drop down only with evidence (profile shows the SQL shape, not EF overhead, is the problem)
  • EF Core's own escape hatches first: projection, ExecuteUpdate/ExecuteDelete, FromSql, Database.SqlQuery<T> for unmapped types (EF Core 8+)
  • Valid reasons: SQL EF can't express (window functions, CTEs, hints, TVPs), bulk loads (SqlBulkCopy), very hot simple reads where materialisation overhead matters
  • Stored procedures fit DBA-owned logic, set-based multi-statement work, security boundaries; cost: deployment coupling, testing, versioning
  • Measure with BenchmarkDotNet for per-call overhead and Query Store/load tests for the real end-to-end gain
  • Keep it contained: Dapper on the DbContext's connection and CurrentTransaction.GetDbTransaction(), read side only, one class per query
  • Version procedure scripts in migrations; parameterise values and allow-list identifiers (ORDER BY columns) that can't be parameters

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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 use FromSql or SqlQuery<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 SqlBulkCopy beats SaveChanges by 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."


The ladder: try in this order

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

Criteria

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

Hidden costs

  • No change tracking or concurrency tokens unless you write them yourself.
  • Hand-written mapping drifts from the schema; renames break at runtime, not at compile time.
  • Migrations don't version stored procedure logic unless you add the procedure scripts to migrations (migrationBuilder.Sql).
  • Two styles to review, test and secure. Raw SQL brings SQL injection back as a risk.

Production example

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.

๐Ÿ” What the interviewer is checking

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

  • Uses EF Core's own escape hatches (SqlQuery<T>, ExecuteUpdate, FromSql) before leaving EF
  • Knows stored procedures aren't faster by default and gives the real reasons to use them
  • Quantifies with BenchmarkDotNet and call rate, and contains raw SQL to the read side and one place
  • Mentions sharing the connection and transaction and keeping SQL parameterised

Red flags

  • "ORMs are slow, always use Dapper" or "never write SQL"
  • No measurement behind the decision
  • Ignores injection risk or transaction consistency when mixing tools

๐Ÿ“š Learn in depth

1. Where the time goes in an EF Core query

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.

2. EF Core's own raw SQL tools

  • 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.
  • The interpolated forms create parameters. The *Raw forms with string concatenation are where injection creeps in.

3. Dapper alongside EF Core

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.

4. Stored procedures: what they do and don't give you

  • Not a speed boost on their own. Parameterised ad hoc SQL gets cached, reusable plans just as procedures do.
  • Real benefits: multi-statement set-based logic runs next to the data with no round trips; DBAs can tune without an app release; EXECUTE permission can be granted without table access.
  • Costs: logic split across two deployables, harder unit testing (you need Testcontainers or a real database), and a versioning contract between the app and the database.

5. Bulk operations

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.

6. Measuring the decision

  1. Micro: BenchmarkDotNet comparing EF tracked, EF projected no-tracking, SqlQuery<T> and Dapper on the same query against a local SQL Server container. Report mean and allocated.
  2. Macro: a load test (k6 or Azure Load Testing) on the endpoint, plus Query Store CPU and reads per execution.
  3. Decision: saving per call ร— calls per second. A 20 ยตs saving at 50 calls/s is 1 ms of CPU per second: not worth a second data-access style.

Try it yourself

  1. Benchmark one read four ways (EF tracked, EF projected, SqlQuery<T>, Dapper) with [MemoryDiagnoser] against SQL Server in Docker.
  2. Rewrite a top-N-per-group report with ROW_NUMBER() in SqlQuery<T> and compare its plan and reads with the LINQ version.
  3. Load 1 million rows with AddRange + SaveChanges and with SqlBulkCopy; compare time and transaction log growth.
  4. Run a Dapper query inside an EF Core transaction and confirm both roll back together.

๐Ÿ’ป Code

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  |

โš  Common mistakes

  • Mistake: Optimising without measuring, for example rewriting the data layer in Dapper "because it's faster". Why it is wrong: For most queries the time is in SQL execution and round trips, not EF overhead, so the rewrite changes nothing measurable. Instead: Profile, benchmark the specific query, and multiply the saving by the call rate.
  • Mistake: Micro-optimising cold paths, such as moving an admin screen's query to a stored procedure. Why it is wrong: You add deployment coupling for zero user-visible gain. Instead: Rank by total cost in Query Store and target the top few.
  • Mistake: Believing stored procedures are inherently faster. Why it is wrong: Parameterised SQL from EF gets cached, reusable plans too. Instead: Choose procedures for set-based multi-statement logic, ownership or security, not for plan caching.
  • Mistake: Building raw SQL with string concatenation or 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.
  • Mistake: Assuming parameterisation covers everything, for example interpolating a sort column into 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.
  • Mistake: Opening a separate connection for Dapper inside a unit of work. Why it is wrong: Writes are not in the same transaction (and with 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.
  • Mistake: Leaving stored procedure scripts out of source control and migrations. Why it is wrong: Environments drift and deployments break silently. Instead: Version procedure scripts in migrations with migrationBuilder.Sql or a database project, and test them against SQL Server in Testcontainers.
  • Mistake: Using Dapper for writes on aggregates with business rules. Why it is wrong: You lose change tracking, concurrency tokens and domain invariants. Instead: Keep writes in EF Core; use raw SQL mainly on the read side.

๐Ÿ› Senior insight: trade-offs

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.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions FromSql or SqlQuery<T> Why: Checks they know the raw SQL APIs in EF Core and how injection still happens.
    How to answer

    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.

  2. When: Candidate mentions SqlBulkCopy or bulk loads Why: Checks they can choose between SaveChanges batching, ExecuteUpdate, SqlBulkCopy and TVPs.
    How to answer

    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.

  3. When: Candidate says they would benchmark EF against Dapper Why: Checks they can write a benchmark whose numbers mean something.
    How to answer

    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:

    • marks one method Baseline = true, so you get a Ratio column;
    • adds [MemoryDiagnoser] for allocated bytes per operation and GC counts;
    • builds inputs in [GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;
    • makes the work observable, by returning the result or consuming the sequence, so the JIT can't remove it as dead code.

    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.

๐Ÿ›  Real-world problems: how you handle them

Monthly statement job too slow for the overnight window
Situation
[Financial services platform] generating [~250,000] customer statements monthly from Azure SQL. The EF Core job took [40 minutes] and was close to overrunning the batch window as volumes grew.
Signals
Job duration trending up month on month; Azure SQL CPU at 100% during the run; Application Insights showing [hundreds of thousands] of small queries from the job.
Investigation
dotnet-trace and Application Insights showed the job loading orders per customer (N+1) and aggregating in LINQ to Objects. Query Store showed the per-customer query was cheap but ran [250,000] times. BenchmarkDotNet on one customer's statement showed EF overhead was minor; the cost was round trips and in-memory aggregation.
Resolution
Immediate: batched customers in pages of [1,000] with one projected query per page, which cut the run to [15 minutes]. Long-term: moved the aggregation into one set-based stored procedure using window functions and a TVP of customer IDs, streamed with Dapper on the EF connection. The run took [3 minutes] and CPU per run fell by [85%]. Interactive APIs stayed on EF Core.
Prevention
ADR recording why this job uses a stored procedure, with the benchmark and Query Store numbers; procedure script versioned in EF migrations; integration test against SQL Server in Testcontainers; duration alert on the job.

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.

More in EF and SQL Performance

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me