Stored procedures versus EF Core and Dapper in a .NET codebase: performance myths, security and permissions, calling procedures from .NET, versioning and deploying them with DACPACs or migrations.
Stored procedures are not automatically faster: parameterised SQL sent by EF Core or Dapper through sp_executesql is compiled and cached the same way. They do win where one call replaces many: set-based multi-step work close to the data cuts round trips, which can turn hours into minutes. Their other strengths are EXECUTE-only permissions so the app login can't touch tables directly, and a stable contract for other consumers. Their costs are logic split across two codebases, harder testing and refactoring, and deployment coordination between the app and the database.
My default is EF Core for CRUD, Dapper or EF raw SQL (always parameterised) for hand-tuned reads, and procedures for heavy batch work. Either way the SQL lives in source control, is tested in CI against a real SQL Server, and ships through the pipeline via a DACPAC or migrations.
"I don't treat it as a religious choice. The old argument that procedures are faster because they're precompiled isn't true any more: when EF Core or Dapper sends parameterised SQL, it goes through sp_executesql, gets compiled on first use and the plan is cached and reused, exactly like a procedure. Both suffer from parameter sniffing the same way.
Where procedures do win is when the work is data-heavy and multi-step. Recalculating loyalty points for a million customers, or a month-end close that touches five tables, is far better done as set-based T-SQL in one call than as thousands of round trips from C#. They also give a clean security model: the app login gets EXECUTE on a schema and no table permissions, so SQL injection or a compromised app has a much smaller blast radius. The costs are real though. Business rules end up split between C# and T-SQL, refactoring tools don't see across the boundary, unit tests need a real database, and every release has to coordinate the app and the database version.
So my default in a .NET 10 service is EF Core for CRUD and most queries, Dapper or EF Core's SqlQuery for the few reads I hand-tune, and stored procedures for batch and data-intensive operations. Whatever I choose, procedures are in source control, reviewed like code, deployed by the pipeline from a SQL project's DACPAC or from migrations, and changed in a backwards-compatible way so the old and new app versions can both run during a rolling deploy. The mistake I see is procedures edited by hand in production with no history, which is how you end up with three versions of the truth."
| Stored procedures | SQL in the app (EF Core/Dapper) | |
|---|---|---|
| Plan caching | Yes | Yes, when parameterised |
| Round trips for multi-step work | One call | Several unless batched |
| Permissions | EXECUTE-only possible | App needs table rights (or schema-level grants) |
| Refactoring and type safety | None across the boundary | Compiler and IDE help (EF Core) |
| Testing | Needs a database (tSQLt, Testcontainers) | Unit and integration tests in .NET |
| Deployment | Must coordinate with app releases | Ships with the app |
| Visibility for DBAs | Easy to find and tune | Need Query Store to find app queries |
| Approach | How | Fits |
|---|---|---|
SDK-style SQL project (Microsoft.Build.Sql) |
Build a DACPAC, SqlPackage /Action:Publish diffs and applies |
Database-first teams, many procedures |
| EF Core migrations | migrationBuilder.Sql("CREATE OR ALTER PROCEDURE ...") |
EF Core owns the schema, few procedures |
| Migration scripts (DbUp, Flyway) | Ordered, idempotent scripts | Teams wanting explicit scripts |
A nightly invoice job used EF Core to load and update each customer's open items, about 600,000 round trips, and took 2 hours 10 minutes. We moved the calculation into one set-based procedure called with a table-valued parameter of customer ids, deployed through the same DACPAC pipeline. It ran in 6 minutes, and the app login lost its direct UPDATE permission on the invoice tables.
Checks whether the candidate can make a balanced, evidence-based choice rather than repeating the "procedures are faster" myth.
Green flags
Red flags
Since SQL Server 7.0, procedures and ad-hoc batches go through the same path: parse, bind, optimise, cache. A procedure's plan is compiled on first execution, not at CREATE time.
EF Core / Dapper Stored procedure
exec sp_executesql N'SELECT ... EXEC dbo.GetOrders @CustomerId = 42
WHERE CustomerId = @p0', ...
| |
v v
plan cache lookup (text hash) plan cache lookup (object id)
| |
compile on miss, reuse on hit compile on miss, reuse on hit
Non-parameterised, concatenated SQL is the thing that bloats the cache, not "ad-hoc SQL" in general.
UPDATE ... FROM with a join beats a C# loop of single-row updates.GRANT EXECUTE ON SCHEMA::app TO AppUser is enough.CommandType.StoredProcedure, typed SqlParameter (set SqlDbType and Size, avoid AddWithValue).QueryAsync<T>("dbo.Proc", args, commandType: CommandType.StoredProcedure).FromSql($"EXEC dbo.Proc {id}") for entity results (not composable), Database.SqlQuery<T> for unmapped types, ExecuteSqlAsync for non-query. Table-valued parameters need a SqlParameter with TypeName.A SQL project (SDK-style Microsoft.Build.Sql) holds the desired state of every object. Building produces a DACPAC; SqlPackage compares it with the target and generates the change script. Use BlockOnPossibleDataLoss=true in pipelines.
For rolling deployments, use expand/contract: add a new parameter with a default, or a GetOrders_v2, deploy the database first, then the app, then remove the old version later.
Release N: DB adds @IncludeArchived bit = 0 (old app still works)
Release N+1: app passes @IncludeArchived
Release N+2: clean-up if needed
Options: tSQLt unit tests inside the database, or integration tests in .NET against a real SQL Server in Testcontainers (mcr.microsoft.com/mssql/server), with the DACPAC or migrations applied first.
sys.dm_exec_cached_plans and sys.dm_exec_query_stats for both.SqlPackage.EXECUTE on a schema only, and confirm it can run the procedure but not SELECT the table.Calling a procedure with a table-valued parameter from .NET 10, using Dapper and EF Core.
CREATE TYPE dbo.IdList AS TABLE (Id int PRIMARY KEY);
GO
CREATE OR ALTER PROCEDURE dbo.RecalculateInvoices
@CustomerIds dbo.IdList READONLY,
@AsOf date
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
UPDATE i
SET i.AmountDue = x.Total
FROM dbo.Invoices i
JOIN (
SELECT l.InvoiceId, SUM(l.Amount) AS Total
FROM dbo.InvoiceLines l
JOIN dbo.Invoices inv ON inv.InvoiceId = l.InvoiceId
JOIN @CustomerIds c ON c.Id = inv.CustomerId
WHERE inv.InvoiceDate <= @AsOf
GROUP BY l.InvoiceId
) x ON x.InvoiceId = i.InvoiceId;
END;
GO
GRANT EXECUTE ON SCHEMA::dbo TO InvoiceApp; -- no table permissions needed
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;
namespace Billing.Infrastructure;
public sealed class InvoiceRecalculator(string connectionString)
{
public async Task RecalculateAsync(IReadOnlyCollection<int> customerIds, DateOnly asOf, CancellationToken ct)
{
var table = new DataTable();
table.Columns.Add("Id", typeof(int));
foreach (var id in customerIds) table.Rows.Add(id);
await using var connection = new SqlConnection(connectionString);
var command = new CommandDefinition(
"dbo.RecalculateInvoices",
new
{
CustomerIds = table.AsTableValuedParameter("dbo.IdList"),
AsOf = asOf.ToDateTime(TimeOnly.MinValue)
},
commandType: CommandType.StoredProcedure,
commandTimeout: 300,
cancellationToken: ct);
await connection.ExecuteAsync(command); // one round trip, set-based work
}
}
// EF Core migration that owns the procedure's definition
public partial class AddRecalculateInvoices : Migration
{
protected override void Up(MigrationBuilder migrationBuilder) =>
migrationBuilder.Sql(File.ReadAllText("Sql/RecalculateInvoices.v2.sql")); // CREATE OR ALTER
protected override void Down(MigrationBuilder migrationBuilder) =>
migrationBuilder.Sql(File.ReadAllText("Sql/RecalculateInvoices.v1.sql"));
}
AddWithValue for procedure parameters. Why it is wrong: Wrong types and sizes cause implicit conversions and many cached plans. Instead: Set SqlDbType and Size explicitly.FromSqlRaw/Dapper with string concatenation, is injectable. Instead: Use sp_executesql with parameters, QUOTENAME for identifiers, and EF Core's interpolated FromSql, which turns holes into parameters.The senior answer is about ownership and change, not speed. Ask who maintains the logic, how it's tested and how it's deployed. A small team shipping a .NET service weekly usually moves faster with SQL in the app and EF Core migrations. A shared database used by several systems, or heavy set-based batch processing, often justifies procedures with a proper SQL project.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| EF Core LINQ | CRUD, aggregates, team is .NET-first | Generated SQL needs reviewing | Complex batch logic |
| Dapper / raw SQL in app | Hand-tuned reads, reporting | SQL strings to maintain | You need change tracking |
| Stored procedures | Data-heavy multi-step work, EXECUTE-only security, shared DB | Two codebases, deploy coordination | Simple CRUD |
Measure before moving logic: count round trips with Application Insights dependency telemetry, and compare duration and logical reads in Query Store before and after.
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.
SQL Server caches compiled plans keyed by the hash of the exact statement text plus plan-affecting SET options and the database. Change one literal or even whitespace and it's a different entry.
SQL built by string concatenation produces a new single-use plan per value: compile CPU, megabytes of cache memory and churn that evicts useful plans. The fix is sp_executesql with typed parameters (what EF Core and Dapper do), plus optimize for ad hoc workloads to store only a stub the first time. Trade-off: reuse saves CPU but means one plan for every value.
How to tell it (STAR)
**S:** Our nightly invoice recalculation at [company] had grown to over two hours and was overlapping the morning window. **T:** I was asked to bring it back under 30 minutes without changing results. **A:** I used Application Insights to show it was making around 600,000 small SQL calls, so latency, not query cost, was the problem. I moved the calculation into a single set-based stored procedure fed by a table-valued parameter, kept it in our SQL project so it went through code review and the DACPAC pipeline, and removed the job's direct table write permissions. **R:** The run dropped to about [6] minutes, and we wrote an ADR on when procedures are the right tool.
Last updated 23 Nov 2026.