Introduction
Creating an order usually involves more than inserting one row. The application may create an order header, add order items, decrease inventory, update totals and possibly record payment or promotion data. If one operation succeeds while another fails, the database can represent a state that never really happened. For example, an order may be confirmed while the product stock remains unchanged.
This lesson reproduces that failure and compares three approaches: a single SaveChangesAsync call, an explicit transaction created with Database.BeginTransactionAsync, and transaction handling that is compatible with a retrying execution strategy. When the provider supports transactions, EF Core normally wraps the changes from one SaveChanges call in a transaction. However, two separate SaveChanges calls are not automatically one user-defined atomic unit. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/saving/transactions?utm_source=openai))
The Failure Scenario
Assume that the application stores products, orders and order items:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int Stock { get; set; }
public decimal UnitPrice { get; set; }
}
public class Order
{
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public decimal Total { get; set; }
public string Status { get; set; } = "Pending";
}
public class OrderItem
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}The following service contains the problem:
public async Task<int> CreateOrderAsync(
int productId,
int quantity,
CancellationToken cancellationToken)
{
var product = await _db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
if (product.Stock < quantity)
throw new InvalidOperationException("Insufficient stock.");
var order = new Order
{
CreatedAt = DateTime.UtcNow,
Total = product.UnitPrice * quantity,
Status = "Confirmed"
};
_db.Orders.Add(order);
await _db.SaveChangesAsync(cancellationToken);
product.Stock -= quantity;
await _db.SaveChangesAsync(cancellationToken);
return order.Id;
}If the first save succeeds and the second save fails because of a transient connection problem, a concurrency conflict or another database error, the order remains while the inventory is not reduced. The first operation has already been committed, so the application is left with inconsistent data. The same problem can occur when ExecuteUpdateAsync, external commands or different DbContext instances are mixed without an explicit transaction. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete?utm_source=openai))
Solution 1: Use One SaveChanges Call
The simplest solution is to prepare all changes in the same context and save them once. EF Core sends the required insert and update commands as part of one save operation. When the provider supports transactions, the operation is atomic: either all changes succeed or the database is left unchanged. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/saving/transactions?utm_source=openai))
public async Task<int> CreateOrderAsync(
int productId,
int quantity,
CancellationToken cancellationToken)
{
var product = await _db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
if (product.Stock < quantity)
throw new InvalidOperationException("Insufficient stock.");
var order = new Order
{
CreatedAt = DateTime.UtcNow,
Total = product.UnitPrice * quantity,
Status = "Confirmed"
};
_db.Orders.Add(order);
product.Stock -= quantity;
await _db.SaveChangesAsync(cancellationToken);
return order.Id;
}This is usually the preferred design for ordinary CRUD workflows. It also lets EF Core order related inserts and updates when the entities belong to the same tracked graph. Nevertheless, an explicit transaction may be necessary when the workflow requires multiple save calls, multiple contexts, raw database commands or several operations that must share one transaction boundary.
Solution 2: BeginTransactionAsync
To group multiple save operations into one atomic unit, begin a transaction explicitly. If the transaction is committed, all operations become permanent. If it is rolled back, the operations inside the transaction are undone. BeginTransactionAsync starts a transaction asynchronously and returns an IDbContextTransaction. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/saving/transactions?utm_source=openai))
public async Task<int> CreateOrderWithTransactionAsync(
int productId,
int quantity,
CancellationToken cancellationToken)
{
await using var transaction =
await _db.Database.BeginTransactionAsync(cancellationToken);
try
{
var product = await _db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
if (product.Stock < quantity)
throw new InvalidOperationException("Insufficient stock.");
var order = new Order
{
CreatedAt = DateTime.UtcNow,
Total = product.UnitPrice * quantity,
Status = "Confirmed"
};
_db.Orders.Add(order);
await _db.SaveChangesAsync(cancellationToken);
product.Stock -= quantity;
await _db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return order.Id;
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}
}The commit is delayed until every database operation succeeds. If any exception occurs, the rollback path runs and the exception is rethrown so that the upper layer can return an appropriate failure response. Swallowing the exception and returning success would make the client believe that the order was completed.
Keep the transaction short. Do not wait for user input, send email or call an external HTTP service while holding a database transaction. A local database transaction cannot automatically undo an email or an external service call. Such workflows usually require an outbox or another integration pattern.
Retrying Execution Strategies and Transactions
Providers such as SQL Server can be configured to retry transient failures with EnableRetryOnFailure. With retries enabled, EF Core treats each query and each SaveChangesAsync call as an independently retryable operation. If application code starts a user transaction directly, the execution strategy cannot replay the entire group and may throw an exception. The recommended pattern is to place the complete transaction delegate inside CreateExecutionStrategy().ExecuteAsync. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency?utm_source=openai))
services.AddDbContext<ShopDbContext>(options =>
options.UseSqlServer(connectionString, sql =>
sql.EnableRetryOnFailure()));public async Task<int> CreateOrderResilientAsync(
int productId,
int quantity,
CancellationToken cancellationToken)
{
var strategy = _db.Database.CreateExecutionStrategy();
var orderId = 0;
await strategy.ExecuteAsync(async () =>
{
await using var transaction =
await _db.Database.BeginTransactionAsync(cancellationToken);
var product = await _db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
if (product.Stock < quantity)
throw new InvalidOperationException("Insufficient stock.");
var order = new Order
{
CreatedAt = DateTime.UtcNow,
Total = product.UnitPrice * quantity,
Status = "Confirmed"
};
_db.Orders.Add(order);
product.Stock -= quantity;
await _db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
orderId = order.Id;
});
return orderId;
}The delegate should be safe to execute again. A connection can fail during commit, leaving the client uncertain about whether the transaction was committed. Retrying an insert with a store-generated key may create a duplicate record if the first commit actually succeeded. Client-generated identifiers, verification queries or a transaction-status table can help make the operation safer. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency?utm_source=openai))
Common Mistakes
- Calling SaveChanges after every small step: If the steps form one business operation, prefer one save call or an explicit transaction.
- Committing too early: Committing before inventory is updated can permanently separate the order from the stock change.
- Rolling back only selected exceptions: Unexpected failures inside the transaction must also reach the rollback path.
- Swallowing exceptions: Log the failure, return an appropriate error and do not report success.
- Combining retries and manual transactions incorrectly: With a retrying strategy, execute the complete transaction as one retryable delegate.
- Using one DbContext concurrently: Do not run parallel asynchronous operations on the same context; await each operation immediately. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.begintransactionasync?view=efcore-10.0&utm_source=openai))
- Ignoring savepoint limitations: EF Core can create savepoints before SaveChanges inside an existing transaction, but SQL Server Multiple Active Result Sets can prevent savepoints from being created. ([learn.microsoft.com](https://learn.microsoft.com/en-us/ef/core/saving/transactions?utm_source=openai))
Practice Exercise
- Write a service that inserts an order and then decreases stock using two separate
SaveChangesAsynccalls. - Throw a controlled exception before the second call and inspect the database. Confirm that the order remains while stock is unchanged.
- Refactor the service to use one
SaveChangesAsynccall. - Refactor it again so the two save calls are enclosed by
BeginTransactionAsync,CommitAsyncandRollbackAsync. - Enable
EnableRetryOnFailureand move the transaction intoCreateExecutionStrategy().ExecuteAsync. - Compare SQL logs and final database state for success and failure. Verify that successful requests create the order and decrease stock, while failed requests leave neither change persisted.
Conclusion
Atomicity is a fundamental reliability requirement when order and inventory changes belong to the same business operation. Prefer one SaveChangesAsync call whenever all changes can be prepared together. Use BeginTransactionAsync when several saves or database commands must share one boundary. If a retrying execution strategy is enabled, put the complete transaction inside a retryable execution delegate.
Reliable transaction handling is more than adding a try/catch block. You must define the correct transaction boundary, delay the commit, handle rollback correctly, consider replay and idempotency, and plan for uncertainty during commit. These practices reduce half-created orders, incorrect inventory and silent production inconsistencies.