Nutshell Series

Unit of Work Pattern in a Nutshell

The Unit of Work Pattern is used to save multiple database changes as one single transaction.

It makes sure that either all changes are saved or none of them are saved.

Simple Example

When placing an order, the system may need to:

  • Create an order
  • Reduce product stock
  • Save payment details

If one step fails, the other changes should not be saved. Unit of Work helps manage this safely.

Key Idea

Do multiple operations
Save everything once

C# Example

public interface IUnitOfWork
{
    Task SaveChangesAsync();
}
public class UnitOfWork : IUnitOfWork
{
    private readonly AppDbContext _context;

    public UnitOfWork(AppDbContext context)
    {
        _context = context;
    }

    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
}

Usage

product.Stock -= 1;

orderRepository.Add(order);

await unitOfWork.SaveChangesAsync();

In EF Core

In Entity Framework Core, DbContext already works like a Unit of Work because it tracks changes and saves them together using:

await dbContext.SaveChangesAsync();

Conclusion

Unit of Work means collect all changes first, then save them together once.

Leave a comment