In enterprise ASP.NET Core ERP, accounting, and reporting backends, complex transactional rules and multi-table ledger updates frequently live in MySQL or SQL Server stored procedures. Choosing how C# executes those procedures directly impacts allocation overhead, throughput, and maintainability.
When to Use Dapper vs. Entity Framework Core for Stored Procedures
Use EF Core (FromSqlInterpolated / ExecuteSqlInterpolatedAsync) when your endpoint already tracks domain entities in a DbContext and returns single-shape entity results. Use Dapper when calling high-throughput reporting procedures, reading multiple result sets (QueryMultipleAsync), or binding OUTPUT and return-status parameters with minimal memory allocation.
Comparison: Dapper vs. EF Core 9 on Stored Procedures
| Capability | Dapper (Micro-ORM) | EF Core 9 |
|---|---|---|
| Object materialization overhead | Near raw DbDataReader speed, minimal GC allocations |
Very fast with AsNoTracking(), heavier when change-tracking |
| Multiple result sets in 1 round-trip | Native via QueryMultipleAsync |
Requires dropping down to underlying DbCommand |
OUTPUT & return parameters |
Clean via DynamicParameters |
Verbose SqlParameter / MySqlParameter setup |
| Sharing an EF Core transaction | Supported via dbContext.Database.GetDbTransaction() |
Built-in |
Practical Example: Calling a Stored Procedure With OUTPUT Parameters in Dapper
using System.Data;
using Dapper;
using MySqlConnector; // or Microsoft.Data.SqlClient for SQL Server
public sealed record LedgerEntryDto(long Id, string AccountCode, decimal Amount, DateTime PostedUtc);
public sealed class LedgerReportRepository(string connectionString)
{
public async Task<(IReadOnlyList<LedgerEntryDto> Rows, decimal ClosingBalance)> GetAccountStatementAsync(
int companyId,
int accountId,
DateOnly fromDate,
CancellationToken ct)
{
await using var conn = new MySqlConnection(connectionString);
var p = new DynamicParameters();
p.Add("p_company_id", companyId, DbType.Int32);
p.Add("p_account_id", accountId, DbType.Int32);
p.Add("p_from_date", fromDate.ToDateTime(TimeOnly.MinValue), DbType.Date);
p.Add("p_closing_balance", dbType: DbType.Decimal, direction: ParameterDirection.Output, precision: 18, scale: 2);
var cmd = new CommandDefinition(
commandText: "sp_get_account_statement",
parameters: p,
commandType: CommandType.StoredProcedure,
commandTimeout: 15,
cancellationToken: ct);
var rows = (await conn.QueryAsync<LedgerEntryDto>(cmd)).AsList();
var closingBalance = p.Get<decimal>("p_closing_balance");
return (rows, closingBalance);
}
}
Production Pitfalls That Stall .NET Database Pools
- Never hold a singleton
SqlConnection/MySqlConnection: ADO.NET pools physical sockets automatically under the hood. Instantiate andawait usingconnections per unit of work so connections return to the pool immediately. - Parameter sniffing on skewed tenant sizes: When one enterprise tenant has 5 million rows and another has 500, a cached stored-procedure execution plan compiled for the small tenant can cause timeouts for the large tenant. Benchmark both shapes using our SQL Query Cost Calculator.
- Always propagate
CancellationToken: PassingHttpContext.RequestAbortedintoCommandDefinitioncancels abandoned browser queries instead of tying up DB worker threads.
Reading Multiple Result Sets in 1 Round-Trip (`QueryMultipleAsync`)
Dashboard and invoice-detail endpoints frequently need a header record, line items, and payment history. Making 3 sequential network trips to RDS or Azure SQL adds unnecessary latency; calling a single stored procedure that emits 3 `SELECT` statements and reading them with Dapper’s **`QueryMultipleAsync`** cuts network round-trips by 66%:
public sealed record InvoiceHeaderDto(long Id, string InvoiceNo, string Status, decimal TotalAmount);
public sealed record InvoiceLineDto(long Id, string Sku, int Quantity, decimal UnitPrice);
public sealed record PaymentEventDto(long Id, string GatewayRef, decimal PaidAmount, DateTime PaidUtc);
public async Task<InvoiceFullViewDto?> GetInvoiceAggregateAsync(long invoiceId, CancellationToken ct)
{
await using var conn = new MySqlConnection(_connectionString);
var cmd = new CommandDefinition(
commandText: "sp_get_invoice_full_detail",
parameters: new { p_invoice_id = invoiceId },
commandType: CommandType.StoredProcedure,
cancellationToken: ct);
using var multi = await conn.QueryMultipleAsync(cmd);
var header = await multi.ReadSingleOrDefaultAsync<InvoiceHeaderDto>();
if (header is null) return null;
var lines = (await multi.ReadAsync<InvoiceLineDto>()).AsList();
var payments = (await multi.ReadAsync<PaymentEventDto>()).AsList();
return new InvoiceFullViewDto(header, lines, payments);
}
Sharing a Database Transaction Between EF Core `DbContext` and Dapper
You do **not** have to choose exclusively between EF Core and Dapper across an entire project! One of the cleanest enterprise .NET 9 architectures uses EF Core for standard domain aggregates and migrations, while sharing the active `DbContext` connection and transaction with Dapper for specialized stored procedures:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Dapper;
public async Task CloseAccountingPeriodAsync(AppDbContext db, int periodId, CancellationToken ct)
{
await using var tx = await db.Database.BeginTransactionAsync(ct);
// 1. Standard EF Core entity state update
var period = await db.AccountingPeriods.SingleAsync(p => p.Id == periodId, ct);
period.Status = "Closing";
await db.SaveChangesAsync(ct);
// 2. Execute heavy stored procedure on the SAME connection & transaction via Dapper!
var underlyingConn = db.Database.GetDbConnection();
var underlyingTx = tx.GetDbTransaction();
await underlyingConn.ExecuteAsync(new CommandDefinition(
commandText: "sp_rollup_period_balances",
parameters: new { p_period_id = periodId },
transaction: underlyingTx,
commandType: CommandType.StoredProcedure,
commandTimeout: 60,
cancellationToken: ct));
period.Status = "Closed";
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
Safe Stored-Procedure Execution in EF Core 9 (`SqlQuery` & `FromSqlInterpolated`)
If your team prefers zero third-party NuGet dependencies, EF Core 8/9 added `db.Database.SqlQuery<T>(FormattableString)` to map arbitrary unmapped DTOs without defining keyless `DbSet` entities—while automatically converting C# interpolated strings (`$"CALL sp_get_orders({tenantId}, {status})"`) into **injection-safe `DbParameter` placeholders**! Never concatenate strings into `FromSqlRaw("CALL sp_x(" + userInput + ")")`, which reintroduces classic SQL injection.
observability & OpenTelemetry Tracing for Stored Procedures
- Instrument `MySqlConnector` or `Microsoft.Data.SqlClient` with OpenTelemetry: Enable `AddSqlClientInstrumentation()` in `Program.cs` so slow stored-procedure calls appear directly inside Jaeger, Grafana Tempo, or Datadog waterfall traces alongside HTTP latency.
- Version-control every stored procedure in Git: Never edit stored procedures live in SSMS or phpMyAdmin! Check `CREATE OR REPLACE PROCEDURE` scripts into your migration pipeline (diff schema revisions anytime with our SQL Compare tool).