C# / .NET Compendium PLEN
.NET / C# / Entity Framework Core

Repository + Unit of Work with EF Core - is it still needed?

The traditional Repository pattern

public interface IOrderRepository
{
    Task<Order> GetByIdAsync(int id);
    Task<List<Order>> GetAllAsync();
    void Add(Order order);
    void Remove(Order order);
}

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;
    public OrderRepository(AppDbContext context) => _context = context;

    public async Task<Order> GetByIdAsync(int id) => await _context.Orders.FindAsync(id);
    public async Task<List<Order>> GetAllAsync() => await _context.Orders.ToListAsync();
    public void Add(Order order) => _context.Orders.Add(order);
    public void Remove(Order order) => _context.Orders.Remove(order);
}

Unit of Work - coordinating a transaction across repositories

public interface IUnitOfWork
{
    IOrderRepository Orders { get; }
    ICustomerRepository Customers { get; }
    Task<int> SaveChangesAsync();
}

public class UnitOfWork : IUnitOfWork
{
    private readonly AppDbContext _context;
    public IOrderRepository Orders { get; }
    public ICustomerRepository Customers { get; }

    public UnitOfWork(AppDbContext context)
    {
        _context = context;
        Orders = new OrderRepository(context);
        Customers = new CustomerRepository(context);
    }

    public async Task<int> SaveChangesAsync() => await _context.SaveChangesAsync(); // JEDNA transakcja
}
// Usage - both changes saved ATOMICALLY in one transaction
await unitOfWork.Orders.AddAsync(order);
await unitOfWork.Customers.UpdateAsync(customer);
await unitOfWork.SaveChangesAsync(); // ONE call, ONE transaction for both changes

The controversy - why many claim it is redundant with EF Core

This is a frequent discussion question in SE III interviews - "is it worth wrapping EF Core in Repository/UoW?" Arguments against:

1. DbContext ALREADY IS a Unit of Work

// DbContext ITSELF tracks all the changes and saves them atomically in ONE transaction
_context.Orders.Add(order);
_context.Customers.Update(customer);
await _context.SaveChangesAsync(); // ONE transaction, with no additional UnitOfWork

SaveChangesAsync() by default wraps all the changes in one transaction - an additional IUnitOfWork duplicates functionality that DbContext already has built in.

2. DbSet<T> ALREADY IS a Repository

// DbSet already has CRUD + LINQ - a "repository" just adds another layer calling the same thing
_context.Orders.Add(order);
_context.Orders.Remove(order);
await _context.Orders.Where(o => o.Status == "Pending").ToListAsync();

3. Losing the power of LINQ/IQueryable - this is the most practical argument, going back to what we discussed with IQueryable:

public interface IOrderRepository
{
    Task<List<Order>> GetAllAsync(); // ❌ Returns EVERYTHING, you can't add a filter from outside as an IQueryable
}

// The service MUST filter in memory, because the Repository has already materialised the data
var orders = await _repository.GetAllAsync();
var filtered = orders.Where(o => o.Status == "Pending"); // a filter IN MEMORY, not in SQL!

To fix this, the repository would have to return IQueryable<Order>, but that leaks EF Core details through the repository interface - which was the main reason the repository was supposed to exist (isolating from a specific data access technology).

When Repository/UoW DOES make sense - arguments FOR

1. A real abstraction from EF Core (a rare but real need) - if you really plan to swap EF Core for something else (Dapper, another ORM), or you test business logic without any database (mocking the whole interface).

2. Encapsulating complex, repeated queries

public interface IOrderRepository
{
    Task<List<Order>> GetOrdersWithPendingPaymentAsync(); // konkretna, nazwana operacja biznesowa
}

public class OrderRepository : IOrderRepository
{
    public async Task<List<Order>> GetOrdersWithPendingPaymentAsync()
    {
        return await _context.Orders
            .Include(o => o.Payments)
            .Where(o => o.Status == "Pending" && o.Payments.All(p => p.Status != "Completed"))
            .ToListAsync();
    }
}

This is a specific repository pattern - not generic CRUD, but named methods corresponding to specific business queries, which encapsulate complex query logic in one place, reusable across many services.

3. CQRS with MediatR - in this pattern (which we talked about) the Handler often calls DbContext directly, with no repository at all - which is, incidentally, the dominant style in modern .NET applications.

A practical recommendation - the dominant view in the .NET community (2020s+)

Don't wrap DbContext in a generic Repository/UoW "just in case" - it adds a layer of abstraction without real benefit, because DbContext/DbSet already are a Unit of Work/Repository. Instead: either call DbContext directly from a service/CQRS Handler, or (if you want encapsulation) create specific repository methods corresponding to concrete business queries (like GetOrdersWithPendingPaymentAsync above), returning already materialised data, not a generic GetAll().

A table - when what

Approach When it makes sense
DbContext directly in a service/Handler The default choice in most modern .NET applications, especially with CQRS
A specific Repository (named business methods) Repeated, complex queries used in many places
A generic IRepository<T>/IUnitOfWork Rarely - mainly when you genuinely test without any database/EF Core, or the company has it as an architectural standard
Buy me a coffee