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

📚 Interview question

Should a .NET team use stored procedures or keep SQL in the application with EF Core or Dapper? Give the real pros and cons, show how you call a procedure from .NET, and explain how you handle permissions, versioning and deployment (for example DACPAC or migrations).

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.

Mid-Level Theory Intermediate dacpac dapper database-deployment ef-core sql-server stored-procedures

🎯 Key points

  • Parameterised ad-hoc SQL (sp_executesql) gets cached plans too; procedures are not automatically faster
  • Real procedure wins: set-based multi-step work near the data, fewer round trips, EXECUTE-only permissions
  • Costs: logic split across two codebases, harder unit testing and refactoring, deploy coordination
  • Call with CommandType.StoredProcedure, typed SqlParameters, Dapper or EF Core FromSql/ExecuteSql
  • SQL injection is about parameterisation, not procedures: FromSqlRaw with concatenation or dynamic SQL inside a procedure is still injectable
  • Version procedures in source control: SDK-style SQL project (DACPAC) or EF Core migrations with CREATE OR ALTER
  • Test procedures in CI with tSQLt or Testcontainers against real SQL Server
  • Deploy backwards-compatible changes first (expand/contract) so old and new app versions both work

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Pros and cons

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

Deployment options

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can make a balanced, evidence-based choice rather than repeating the "procedures are faster" myth.

Green flags

  • Explains that parameterised SQL is cached like a procedure
  • Names real benefits: round trips, set-based work, EXECUTE-only permissions
  • Has a deployment story (DACPAC, migrations, expand/contract)
  • Knows how to call procedures from Dapper and EF Core, including TVPs

Red flags

  • "Procedures are always faster" or "never use procedures"
  • No version control or deployment plan for database code
  • Builds dynamic SQL by concatenation inside procedures

📚 Learn in depth

1. Why the "precompiled" myth is wrong

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.

2. Where procedures really help

  • Round trips: each call from Azure App Service to Azure SQL costs about 1-2 ms in the same region. 10,000 calls is 10-20 seconds of pure network wait.
  • Set-based work: one UPDATE ... FROM with a join beats a C# loop of single-row updates.
  • Ownership chaining: if the procedure and tables share an owner, GRANT EXECUTE ON SCHEMA::app TO AppUser is enough.

3. Calling procedures from .NET

  • ADO.NET: CommandType.StoredProcedure, typed SqlParameter (set SqlDbType and Size, avoid AddWithValue).
  • Dapper: QueryAsync<T>("dbo.Proc", args, commandType: CommandType.StoredProcedure).
  • EF Core: 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.

4. Versioning and deployment

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

5. Testing

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.

Try it yourself

  1. Run the same parameterised query via Dapper and as a procedure, then inspect sys.dm_exec_cached_plans and sys.dm_exec_query_stats for both.
  2. Create an SDK-style SQL project, add a procedure, build the DACPAC and publish to a local container with SqlPackage.
  3. Grant a test login EXECUTE on a schema only, and confirm it can run the procedure but not SELECT the table.
  4. Write a Testcontainers test that calls a procedure with a table-valued parameter.

💻 Code

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"));
}

⚠ Common mistakes

  • Mistake: Claiming procedures are faster because they are precompiled. Why it is wrong: Plans are compiled on first execution and parameterised ad-hoc SQL is cached the same way. Instead: Argue from round trips, set-based work and permissions.
  • Mistake: Editing procedures directly in production. Why it is wrong: There is no history or review, environments drift, the next DACPAC publish silently reverts the hotfix, and nobody can roll back to a known version. Instead: Keep them in a SQL project or migrations and deploy every change through the pipeline, even urgent ones.
  • Mistake: Putting the same business rule in procedures and in C#. Why it is wrong: The two copies drift as the app evolves; a change made in C# is missed in T-SQL, and nobody can see or test the whole rule in one place. Instead: Decide where each rule lives: procedures for data-intensive operations, domain rules in the app, and document the boundary in an ADR.
  • Mistake: Changing a procedure's parameters in a breaking way during a rolling deploy. Why it is wrong: Old app instances still call the old signature and fail. Instead: Add optional parameters with defaults or a versioned procedure (expand/contract).
  • Mistake: Using 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.
  • Mistake: Assuming procedures or EF Core make you safe from SQL injection. Why it is wrong: Dynamic SQL concatenated inside a procedure, or 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.
  • Mistake: Leaving procedures untested because they "live in the database". Why it is wrong: Regressions only show up in production. Instead: Run tSQLt tests or Testcontainers integration tests in CI after applying the DACPAC or migrations.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions calling procedures through EF Core Why: Checks safe use of FromSql, SqlQuery and ExecuteSql and the injection risk of FromSqlRaw.
    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 says ad-hoc SQL gets cached plans too Why: Checks understanding of plan matching, parameterisation and plan cache bloat.
    How to answer

    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.

    • Simple parameterisation (default) only auto-parameterises very simple, safe queries.
    • Forced parameterisation replaces most literals with parameters, cutting compiles but adding parameter sniffing.

    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.

🛠 Real-world problems: how you handle them

Nightly invoice job doing 600,000 round trips
Situation
A [billing service] on Azure App Service recalculated open invoices nightly for [about 120,000] customers using EF Core, loading and saving each customer's invoices one at a time against Azure SQL in [Australia East].
Signals
The job's duration crept from 40 minutes to over 2 hours as customers grew; it started overlapping the morning batch window. Application Insights showed about 600,000 SQL dependency calls per run averaging 4 ms each, and DTU usage stayed moderate, so the database wasn't the bottleneck.
Investigation
Grouped Application Insights dependencies by operation to see the call count per customer. Captured the generated SQL and confirmed each was a cheap single-row read or update. Checked Query Store: no individual query was expensive. Calculated that network round trips alone accounted for most of the duration.
Resolution
Short term, batched the EF Core updates with ExecuteUpdateAsync per customer group. Long term, wrote one set-based procedure taking a table-valued parameter of customer ids in batches of 5,000, added it to the SQL project and deployed it through the DACPAC pipeline. Granted the job's login EXECUTE only.
Prevention
Added an alert on dependency call count per job run, a Testcontainers integration test for the procedure, and a team guideline that batch jobs must not do per-row round trips. Recorded the decision in an ADR describing when procedures are allowed.

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.

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me