In EF Core 10, how do you make an order placement that writes through two different DbContext types commit or roll back as one transaction?
answer
- same DbConnection, same DbTransaction
- Database.UseTransaction(tx.GetDbTransaction())
- relational providers only
- TransactionScopeAsyncFlowOption.Enabled
- distributed transactions: Windows only
basics
~20 sGive both contexts the same DbConnection, begin the transaction on one, and enlist the other with Database.UseTransaction(tx.GetDbTransaction()); then save both and commit once. A TransactionScope also works, but two connections inside it need a distributed transaction.
solid answer
~40 sA `DbContext` only joins a transaction that belongs to its own connection, so both contexts must share one `DbConnection` - create it yourself and pass it to `UseNpgsql(connection)` for each, or point a DI-created context at it with `Database.SetDbConnection` before it opens. Then `await using var tx = await ordering.Database.BeginTransactionAsync()`, call `inventory.Database.UseTransaction(tx.GetDbTransaction())`, save both contexts and `CommitAsync` once. Passing a transaction from a different connection throws an `InvalidOperationException`. The alternative is an ambient `TransactionScope` created with `TransactionScopeAsyncFlowOption.Enabled`: EF Core enlists in it, but two separate connections in one scope need a distributed transaction, which .NET supports only on Windows, and the scope has no async commit. Often the simpler fix is one context, or one `SaveChanges`.
code
csharp · 16 linesawait using var connection = dataSource.CreateConnection(); // one NpgsqlConnection
await using var ordering = new OrderingContext(
new DbContextOptionsBuilder<OrderingContext>().UseNpgsql(connection).Options);
await using var inventory = new InventoryContext(
new DbContextOptionsBuilder<InventoryContext>().UseNpgsql(connection).Options);
await using var tx = await ordering.Database.BeginTransactionAsync(ct);
await inventory.Database.UseTransactionAsync(tx.GetDbTransaction(), ct);
ordering.Orders.Add(order);
await ordering.SaveChangesAsync(ct);
foreach (var line in order.Lines)
(await inventory.StockLevels.SingleAsync(s => s.PastryId == line.PastryId, ct)).OnHand -= line.Quantity;
await inventory.SaveChangesAsync(ct);
await tx.CommitAsync(ct);go deeper
Know that two contexts mean two transactions unless you deliberately share one.
Explain why both contexts need the same DbConnection, and how BeginTransactionAsync, GetDbTransaction and UseTransaction fit together.
Weigh shared connections against TransactionScope, with its async-flow option, distribution and synchronous commit, and against merging the write into one context.
Decide whether bounded contexts that must commit together belong in one DbContext, or whether the business can accept eventual consistency between them.
## The problem A bakery chain splits its model in two: `OrderingContext` owns orders and order lines, `InventoryContext` owns stock levels. Both map tables in the **same PostgreSQL database**. Placing an order must insert the order and lower stock, and the two writes must not diverge: a committed order with unchanged stock, or reduced stock with no order, is a bug. Each `DbContext` has its own `SaveChanges` and, by default, its own connection - so two `SaveChangesAsync` calls are two separate transactions. Something has to make them one. ## Option 1 - share the connection and the transaction This works with relational providers only, because it relies on ADO.NET's `DbConnection` and `DbTransaction`. 1. **One connection for both contexts.** A transaction belongs to a connection, so the contexts must use the same `DbConnection` object. Either build `DbContextOptions` yourself with `UseNpgsql(connection)` for each context, or, for contexts created by DI, call `Database.SetDbConnection(connection)` before the context has opened its own. 2. **Begin on one context.** `await using var tx = await ordering.Database.BeginTransactionAsync();` 3. **Enlist the other.** `await inventory.Database.UseTransactionAsync(tx.GetDbTransaction());` - `GetDbTransaction()` unwraps EF Core's `IDbContextTransaction` to the ADO.NET `DbTransaction`. 4. **Save both, commit once.** Each `SaveChangesAsync` runs inside the shared transaction (with its automatic savepoint), and `tx.CommitAsync()` makes both durable. If the second context still has its own connection, `UseTransaction` throws an `InvalidOperationException`: "The specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used." The same `UseTransaction` call lets EF Core join a transaction started by plain ADO.NET or Dapper code on that connection. ## Option 2 - an ambient TransactionScope `System.Transactions` lets you open a scope that every enlisting connection joins: ```csharp using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); await ordering.SaveChangesAsync(ct); await inventory.SaveChangesAsync(ct); scope.Complete(); ``` The constraints, from the EF Core docs: - **Provider support.** EF Core relies on the ADO.NET provider to enlist; test that yours does before relying on it. - **Async flow.** Without `TransactionScopeAsyncFlowOption.Enabled`, the ambient transaction does not flow across `await`. - **Distribution.** Two different connections in one scope need a **distributed transaction**, which `System.Transactions` supports only on Windows, from .NET 7. - **No async commit.** Disposing the scope commits or rolls back synchronously, blocking the thread. - **SQL Server in EF Core 10.** EF Core now injects an `Application Name` into SQL Server connection strings that lack one, so EF and plain SqlClient code in one scope use different connection pools and can escalate to a distributed transaction; setting `Application Name` yourself avoids it. ## Option 3 - do not split the write The cleanest answer is often to avoid a cross-context transaction altogether: | Approach | Atomic | Cost | |---|---|---| | one context that maps both orders and stock for this use case | yes, one `SaveChanges` | a wider context | | shared connection + `UseTransaction` | yes | manual connection plumbing | | `TransactionScope` with one connection | yes | provider must enlist; sync commit | | `TransactionScope` with two connections | yes, if distributed transactions are available | Windows-only, heavier protocol | | two independent saves plus a message between them | eventually | a different design, outside this answer | ## Retries change the shape If either context uses `EnableRetryOnFailure`, a transaction you begin yourself must run inside `Database.CreateExecutionStrategy().ExecuteAsync(...)`, and each attempt must rebuild both contexts' work. The execution strategy also refuses an ambient transaction it did not start.
- Both contexts are registered with AddDbContext and resolved in the same request. Why does UseTransaction still fail?Each context created that way builds its own connection from the connection string, so the transaction begun on one is not associated with the other's connection, and `UseTransaction` throws. Hand both the same `DbConnection` - through options you build, or `Database.SetDbConnection` before the second context opens a connection.
- Why must a TransactionScope used around SaveChangesAsync pass TransactionScopeAsyncFlowOption.Enabled?The ambient transaction lives in the execution context; without that option it does not flow across `await`, so code after the first `await` may run outside the scope and its connection would not enlist.
- Two SaveChangesAsync calls in one request are automatically one transaction.
- UseTransaction works with a transaction from any connection to the same database.
- A TransactionScope flows across await without any constructor option.
- Two connections in one TransactionScope work on Linux without extra setup.
- Sharing a transaction across contexts also works on non-relational providers.
Assumes EF Core 10 with the Npgsql provider; on SQL Server, EF Core 10 injects an Application Name into connection strings, so EF and plain SqlClient code under one TransactionScope can now escalate to a distributed transaction.