Skip to main content

Lesson 5 of 8

Transactions & Optimistic Concurrency

Transactions ensure multiple operations either all succeed or all fail atomically. EF Core wraps each SaveChanges call in an implicit transaction. For multi-step operations (create order + deduct inventory + send email task), you need explicit transaction control. Optimistic concurrency prevents lost updates in concurrent environments.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Explicit Transactions & Concurrency Control

Explicit Transactions & Concurrency Control
// ━━ Explicit transaction - multi-operation atomicity ━━
public async Task<Order> PlaceOrderAsync(PlaceOrderCommand command, CancellationToken ct)
{
    await using var transaction = await dbContext.Database.BeginTransactionAsync(
        System.Data.IsolationLevel.ReadCommitted, ct); // explicit isolation level

    try
    {
        // 1. Deduct inventory from each product (must happen atomically with order creation)
        foreach (var item in command.Items)
        {
            var product = await dbContext.Products
                .Where(p => p.Id == item.ProductId)
                .FirstOrDefaultAsync(ct)
                ?? throw new NotFoundException(nameof(Product), item.ProductId);

            if (product.StockQuantity < item.Quantity)
                throw new DomainException($"Insufficient stock for {product.Name}");

            product.StockQuantity -= item.Quantity;
        }

        // 2. Create order
        var order = new Order
        {
            Id = Guid.NewGuid(),
            CustomerId = command.CustomerId,
            Items = command.Items.Select(i => new OrderItem
            {
                Id = Guid.NewGuid(),
                ProductId = i.ProductId,
                Quantity = i.Quantity,
                UnitPrice = i.UnitPrice,
                OrderId = Guid.Empty  // will be set
            }).ToList(),
            Status = "Pending",
            Total = command.Items.Sum(i => i.Quantity * i.UnitPrice)
        };
        dbContext.Orders.Add(order);

        // 3. Both operations in ONE transaction
        await dbContext.SaveChangesAsync(ct);
        await transaction.CommitAsync(ct);

        return order;
    }
    catch
    {
        await transaction.RollbackAsync(ct);
        throw;
    }
}

// ━━ Optimistic concurrency with RowVersion ━━
// Without locking: two users update the same product simultaneously - last write wins (data loss)
// With RowVersion: second save throws DbUpdateConcurrencyException if row changed since read

public async Task UpdateProductAsync(Guid id, UpdateProductRequest request, CancellationToken ct)
{
    var product = await dbContext.Products.FindAsync([id], ct)
        ?? throw new NotFoundException(nameof(Product), id);

    product.Price = request.Price;
    product.Name = request.Name;

    try
    {
        await dbContext.SaveChangesAsync(ct); // throws if RowVersion changed
    }
    catch (Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException ex)
    {
        // Another request modified this record between our read and write
        // Options: 1) Retry with fresh data, 2) Throw 409 Conflict
        throw new ConflictException("Product was modified by another request. Please retry.");
    }
}

// Placeholder types
record PlaceOrderCommand(Guid CustomerId, List<OrderLineItem> Items);
record OrderLineItem(Guid ProductId, int Quantity, decimal UnitPrice);
class DomainException : Exception { public DomainException(string m) : base(m) { } }
class NotFoundException : DomainException { public NotFoundException(string r, object id) : base($"{r} {id} not found") { } }
class ConflictException : DomainException { public ConflictException(string m) : base(m) { } }
record UpdateProductRequest(string Name, decimal Price);
class OrderItem2 { public Guid Id { get; set; } public Guid ProductId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } }

Tip

Tip

Practice Transactions Optimistic Concurrency in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Transactions Optimistic Concurrency from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Transactions Optimistic Concurrency is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done