skip to content

In an ASP.NET Core 10 energy-meter report endpoint mixing EF Core 10 writes with hand-written SQL reads on SQL Server, why can a TransactionScope escalate, and how do you avoid it?

level: seniorimportance: should knowfreq 30%

answer

  1. EF Core 10 rewrites the connection string
  2. Application Name injected when missing
  3. two strings, two SqlClient pools
  4. set Application Name yourself
  5. GetDbConnection() and GetDbTransaction()

basics

~20 s

EF Core 10 injects an Application Name into SQL Server connection strings lacking one, so EF and raw SQL use two strings, pools and connections, and a TransactionScope over both can escalate. Set Application Name, or share EF's connection and transaction.

solid answer

~50 s

Since EF Core 10, the SQL Server provider rewrites a connection string whose `Application Name` is missing or still SqlClient's default, setting it to an `EFCore/<version>` value. My Dapper or ADO.NET code passes the original string, so SqlClient sees two different strings, keeps two pools and opens two connections. Inside one `TransactionScope`, two connections that SqlClient treats as distinct resources make the transaction escalate to a distributed one, which is heavier and needs a coordinator. The cheap fix is to set `Application Name=MeterReports` in the shared string; EF then leaves it unchanged and both sides share one pool again, as before EF Core 10. The more robust fix skips `TransactionScope`: start the transaction with `db.Database.BeginTransactionAsync()`, run the hand-written SQL on `db.Database.GetDbConnection()` with `tx.GetDbTransaction()`, then `SaveChangesAsync` and commit. Per query, I keep EF Core for writes through the model and use Dapper or ADO.NET for heavy report reads.

go deeper

for a junior

Know that one endpoint can use EF Core for writes and Dapper or ADO.NET for heavy reads against the same database.

for a middle

Explain how a connection string identifies a SqlClient pool, and why EF Core 10's injected Application Name splits EF and raw SQL into two pools.

for a senior

Diagnose a distributed-transaction escalation after an EF Core 10 upgrade, and fix it with an explicit Application Name or a shared EF connection and transaction.

for a principal

Set the rule for which queries leave the ORM and how mixed-tool transactions are written, so upgrades cannot silently change transaction behaviour.

## Choosing the tool per query An energy-meter platform rarely needs one data-access tool for everything. A report endpoint typically does both: | Work | Tool | Why | |---|---|---| | Saving a `MonthlyReport` with rules on the model | EF Core | change tracking, `SaveChangesAsync`, migrations own the schema | | Aggregating millions of readings with window functions | Dapper or ADO.NET | exact SQL, results mapped straight into DTOs, nothing tracked | | Loading a tariff for display | EF Core projection | typed LINQ, no hand-written SQL to maintain | | Importing a day of readings | the driver's bulk API (`SqlBulkCopy`, Npgsql's binary COPY) | row-by-row inserts are far slower | Mixing tools is fine. Mixing **connections** inside one transaction is where EF Core 10 changed the picture. ## What EF Core 10 does to the connection string The SQL Server provider's connection now runs the user's string through a small rewrite: if `Application Name` is empty, absent, or still SqlClient's own default ("Core Microsoft SqlClient Data Provider"), EF Core sets it to a value of the form `EFCore/<version> (<OS> <architecture>)`. A string that already names an application is left exactly as it was. EF Core's breaking-changes list for 10.0 records this as a low-impact change. ## Why a TransactionScope can now escalate 1. The handler opens a `TransactionScope` and reads with Dapper using the configured string. 2. It saves through the `DbContext`, which connects with the **rewritten** string. 3. SqlClient keys pools by connection string, so it opens a second physical connection from a second pool, and treats the two as distinct resources. 4. Two resources in one ambient transaction cause escalation to a **distributed transaction**, which is far heavier than a local one and needs a transaction coordinator. Before EF Core 10 the strings matched and the same code could stay local. ## Fix 1: name the application yourself ```json { "ConnectionStrings": { "Meters": "Server=sql;Database=Meters;Application Name=MeterReports;Encrypt=True" } } ``` With an explicit name, EF Core keeps the string byte for byte, both sides share one pool, and monitoring on the server shows a meaningful application name. That restores the pre-10 behaviour: when the Dapper connection is closed before EF Core opens its own, SqlClient can hand back the connection already enlisted in the transaction, so it stays local. Two connections open at the same moment inside one scope can still escalate, which is why Fix 2 is sturdier. Setting it to SqlClient's default text does not help, because EF Core overwrites that value too. ## Fix 2: share EF Core's connection and transaction ```csharp await using var tx = await db.Database.BeginTransactionAsync(); var conn = db.Database.GetDbConnection(); // opened by BeginTransactionAsync await using var cmd = conn.CreateCommand(); cmd.Transaction = tx.GetDbTransaction(); cmd.CommandText = "SELECT SUM(kwh) FROM meter_readings WHERE site_id = @site AND read_at >= @from"; // add @site and @from parameters, then run ExecuteScalarAsync db.MonthlyReports.Add(report); await db.SaveChangesAsync(); await tx.CommitAsync(); ``` One connection, one local transaction, no ambient scope. With Dapper, pass `tx.GetDbTransaction()` as the transaction argument. The connection belongs to the context, so do not dispose it yourself. ## On PostgreSQL The Npgsql provider does not inject an `Application Name`. To keep EF Core and Dapper on one pool there, give EF the same data source: `AddDbContext<MeterDbContext>((sp, o) => o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>()))`. ## Upgrading to EF Core 10 safely The rewrite is silent: nothing fails at startup, and most apps never notice. Look for it when an upgrade is followed by: - errors or slowdowns around `TransactionScope` blocks that combine a `DbContext` with Dapper or ADO.NET; - twice as many server connections from one service as before; - server-side monitoring listing an `EFCore/10...` application name next to your own. Adding an explicit `Application Name` to every SQL Server connection string before the upgrade removes the whole class of surprise. ## Checklist - keep one connection string per database, with an explicit `Application Name` on SQL Server; - prefer an explicit EF transaction over `TransactionScope` when EF and raw SQL must commit together; - run the raw SQL on `GetDbConnection()` with the EF transaction attached; - keep each tool on the queries it serves best.

  • The report endpoint uses Dapper and EF Core 10 on SQL Server but never inside one transaction. Does the injected Application Name still matter?
    Less, but yes. The two sides draw from two pools of up to 100 connections each (Max Pool Size), so the app can open more server connections than planned, and server-side monitoring shows two application names for one service. Setting `Application Name` explicitly restores one pool and one recognisable name.
  • On PostgreSQL, how do EF Core and Dapper end up sharing one Npgsql pool in an ASP.NET Core app?
    Register the data source once with `AddNpgsqlDataSource(cs)` and configure the context from it: `AddDbContext<MeterDbContext>((sp, o) => o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>()))`. Dapper code injects the same `NpgsqlDataSource`, so both draw connections from one pool with one set of limits.

  • EF Core 10 sends the configured SQL Server connection string exactly as written.
  • Setting Application Name to SqlClient's default value stops EF Core rewriting it.
  • Dapper and EF Core always share one pool when they read the same configuration key.
  • Use EF Core for every query, since Dapper cannot coexist with a DbContext.
  • Dispose the connection from GetDbConnection() after running the hand-written SQL.

Assumes EF Core 10 with Microsoft.Data.SqlClient on .NET 10; EF Core 10 began injecting an Application Name into SQL Server connection strings that lack one.