
SaveChanges Is Already a Transaction: When You Actually Need an Explicit One
- كاتب موثّق
- EF Core 10
محتويات المقال
BeginTransactionAsync and CommitAsync, tests pass, and the change ships to staging, which runs on Azure SQL with EnableRetryOnFailure. Every checkout now fails with InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. The transaction that broke checkout wasn't protecting anything the original code needed protecting.
The common misconception
SaveChanges sends its INSERT, UPDATE and DELETE statements one by one, so if the third one fails, the first two stay in the database. To make several changes atomic, you have to open a transaction around them yourself.
SaveChanges sending separate statements, which looks like separate operations. Plenty of tutorials and repository templates wrap every save in BeginTransaction, and being explicit feels safer than trusting a default you can't see.
What actually happens
One SaveChanges, one transaction
SaveChanges call are applied in a transaction, and if any of them fails, the transaction is rolled back. The call either succeeds completely or leaves the database unchanged.
SaveChanges inserted an order and its two lines and deleted the customer's cart. The log showed Began transaction, the statements, then Committed transaction. When one line broke a CHECK constraint, the call threw DbUpdateException and the database held no order, no lines, and the same cart as before. The new order stayed Added in the change tracker, so the call can be fixed and retried.
AutoTransactionBehavior.WhenNeeded, the default, EF skips the explicit transaction when SaveChanges needs only one statement, because a single statement is already atomic. In the test, saving one changed product sent a lone UPDATE, with no Began transaction.
You rarely need two SaveChanges
Id, then set OrderId on each line. You don't need to. Add the lines through the Order.Lines navigation and EF Core inserts the order first, reads back its generated key and fills in OrderId on each line, all within the same call. In the test, both lines came back with the new order's Id after one SaveChanges.
Inside your transaction, SaveChanges uses a savepoint
SaveChanges creates a before writing and rolls back to it if it fails, so a failed save doesn't ruin the work before it in the same transaction. In the test, the log showed Created transaction savepoint for each call inside an explicit transaction. On SQL Server, EF doesn't create savepoints when MARS is enabled on the connection.
Where an explicit transaction earns its place
SaveChanges calls where the second failed left an order with no lines. ExecuteUpdate and ExecuteDelete run immediately, outside SaveChanges: an ExecuteDelete of the cart's items followed by a failing SaveChanges left the items deleted and no order. The same applies to raw SQL, to Dapper or ADO.NET sharing the connection, and to a read that must stay valid until the write.
The fix: one call, built as a graph
using Microsoft.EntityFrameworkCore;public sealed class PlaceOrder(ShopDb db){ public async Task<int> RunAsync(int cartId, CancellationToken ct) { // Needed only because the save is split; throws when retries are on await using var tx = await db.Database.BeginTransactionAsync(ct); var cart = await db.Carts.Include(c => c.Items) .SingleAsync(c => c.Id == cartId, ct); var order = new Order { CustomerId = cart.CustomerId }; db.Orders.Add(order); await db.SaveChangesAsync(ct); // only to get order.Id db.OrderLines.AddRange(cart.Items.Select(i => i.ToLine(order.Id))); db.Carts.Remove(cart); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); return order.Id; }}using Microsoft.EntityFrameworkCore;public sealed class PlaceOrder(ShopDb db){ public async Task<int> RunAsync(int cartId, CancellationToken ct) { var cart = await db.Carts.Include(c => c.Items) .SingleAsync(c => c.Id == cartId, ct); var order = new Order { CustomerId = cart.CustomerId }; // Lines join through the navigation; EF sets OrderId during the save order.Lines.AddRange(cart.Items.Select(i => i.ToLine())); db.Orders.Add(order); db.Carts.Remove(cart); // its tracked items are deleted with it // One call, one transaction: order, lines and cart, all or nothing await db.SaveChangesAsync(ct); return order.Id; }}SaveChanges call as one unit. In the test, which used a custom retrying strategy on SQLite, the wrong version threw the same "does not support user-initiated transactions" error, and the right one saved everything.
When you do need one
ExecuteUpdate, so the database does the arithmetic and two concurrent orders can't overwrite each other's decrement. That statement runs on its own, so it and the SaveChanges must share a transaction. Keep it to rows the context isn't tracking, since ExecuteUpdate doesn't update tracked entities. With retries enabled, run the whole block through the execution strategy:
using Microsoft.EntityFrameworkCore;public sealed class OrderSaver(ShopDb db){ public async Task SaveAsync(int productId, int qty, CancellationToken ct) { var strategy = db.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { await using var tx = await db.Database.BeginTransactionAsync(ct); // Runs right away, outside SaveChanges: only tx ties the two together await db.Products.Where(p => p.Id == productId).ExecuteUpdateAsync( s => s.SetProperty(p => p.Stock, p => p.Stock - qty), ct); // false keeps entity states, so a replay saves them again await db.SaveChangesAsync(acceptAllChangesOnSuccess: false, ct); await tx.CommitAsync(ct); }); db.ChangeTracker.AcceptAllChanges(); }}SaveChanges failed, the stock decrement was rolled back with it.
SaveChanges | |
SaveChanges calls that must succeed together | |
ExecuteUpdate, ExecuteDelete or raw SQL next to SaveChanges | |
UseTransaction |
How to apply it in your project
Remove transactions that wrap one SaveChanges Search for BeginTransaction. Where it wraps a singleSaveChangesand nothing else, delete it: the call is already atomic.Merge saves that were split for keys If a save exists only to get a generated Id, connect the entities through navigations and save the graph once.Keep transactions for multi-call work Keep an explicit transaction where SaveChangessits next toExecuteUpdate,ExecuteDelete, raw SQL, another context or another data access library.Run them through the execution strategy If you use EnableRetryOnFailure, wrap each explicit transaction inCreateExecutionStrategy().ExecuteAsync, make the delegate safe to replay, and save withacceptAllChangesOnSuccess: false.
Key takeaways
One SaveChangescall is one transaction: all of its changes are applied, or none are.Generated keys don't require two saves; add the graph through navigations and save once. Explicit transactions are for units of work that span several calls: multiple saves, ExecuteUpdate,ExecuteDelete, raw SQL or shared connections.ExecuteUpdateandExecuteDeleterun immediately and aren't part of anySaveChangestransaction.With a retrying execution strategy, put explicit transactions inside CreateExecutionStrategy().ExecuteAsyncand keep the delegate replayable.
التعليقات (0)