الانتقال إلى المحتوى
.NETEF Core· 8 دقائق للقراءة

SaveChanges Is Already a Transaction: When You Actually Need an Explicit One

Every change in one SaveChanges call succeeds or fails together. An explicit transaction is for work that spans more than one call.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A pull request adds order placement, and a reviewer leaves a comment: "Wrap this in a transaction, or we could end up with an order and no lines." The author adds 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

The belief: 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.

It's a reasonable belief. With raw ADO.NET or Dapper, each command commits on its own unless you start a transaction, and that's how many developers learned data access. The SQL log shows 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

EF Core's documented default: if the database provider supports transactions, all the changes in one 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.

In a test with EF Core 10 and SQLite, one 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.

There's one refinement: with 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

A common reason for splitting a save is the generated key: save the order first to get its 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

When a transaction is already in progress, 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

An explicit transaction is for a that spans several database calls. Without one, each call commits on its own. In the test, two 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

C# PlaceOrder.cs
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;    }}

The right version builds the whole change as a graph and saves it once. It's atomic without any transaction code, and it works unchanged under a retrying , because the strategy can replay a single 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

Say you decrement stock with 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:

C# OrderSaver.cs
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();    }}

In the test, when the SaveChanges failed, the stock decrement was rolled back with it.

SituationExplicit transaction?
Several adds, updates and deletes in one SaveChangesNo: already atomic
A parent and children with generated keysNo: add the graph and save once
Two or more SaveChanges calls that must succeed togetherYes
ExecuteUpdate, ExecuteDelete or raw SQL next to SaveChangesYes
EF Core and Dapper or ADO.NET on the same connectionYes, shared with UseTransaction

How to apply it in your project

  1. Remove transactions that wrap one SaveChangesSearch for BeginTransaction. Where it wraps a single SaveChanges and nothing else, delete it: the call is already atomic.
  2. Merge saves that were split for keysIf a save exists only to get a generated Id, connect the entities through navigations and save the graph once.
  3. Keep transactions for multi-call workKeep an explicit transaction where SaveChanges sits next to ExecuteUpdate, ExecuteDelete, raw SQL, another context or another data access library.
  4. Run them through the execution strategyIf you use EnableRetryOnFailure, wrap each explicit transaction in CreateExecutionStrategy().ExecuteAsync, make the delegate safe to replay, and save with acceptAllChangesOnSuccess: false.

Key takeaways

  • One SaveChanges call 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.
  • ExecuteUpdate and ExecuteDelete run immediately and aren't part of any SaveChanges transaction.
  • With a retrying execution strategy, put explicit transactions inside CreateExecutionStrategy().ExecuteAsync and keep the delegate replayable.

📚 المصادر

  1. Transactions — EF Core, Microsoft Learn
  2. Basic SaveChanges — EF Core, Microsoft Learn
  3. Connection Resiliency — EF Core, Microsoft Learn
  4. ExecuteUpdate and ExecuteDelete — EF Core, Microsoft Learn

التعليقات (0)