
Do You Need a Repository on Top of EF Core? The Honest Trade-offs
- كاتب موثّق
- EF Core 10
محتويات المقال
Repository<T> with Query(), Add, Update and Delete, and a UnitOfWork class with a repository property for every entity. The first checkout handler needs an order with its lines, so it calls orders.Query().Include(o => o.Lines).SingleAsync(...), and the Application project gains a package reference to EF Core for Include and SingleAsync. Its unit test stubs Query() with a list and fails with The source 'IQueryable' doesn't implement 'IAsyncEnumerable<Order>'. Two layers of abstraction later, the use case still depends on EF Core and still can't be tested without a database.
The common misconception
DbContext, and the wrapper is what makes it testable and lets you swap the ORM later.
What actually happens
DbContext already is both patterns
DbContext is a combination of the Unit Of Work and Repository patterns. Fowler defines a repository as mediating between the domain and data mapping layers through a collection-like interface, which is what DbSet<T> is. The collects changes and commits them together, which is SaveChanges. Microsoft's guide notes that its own repositories rely on the DbContext implementation of both patterns instead of duplicating it. A generic IRepository<T> plus a UnitOfWork class re-declares both, with fewer features.
The rule is about direction, not wrappers
It returns IQueryable<T>. Callers needInclude,AsNoTrackingandSingleAsync, all extension methods from EF Core, so the dependency comes straight back. Microsoft's testing guide adds that a repository exposingIQueryablecan't be stubbed reliably; in a test, a list'sAsQueryable()threw theIAsyncEnumerableerror above.It returns lists from GetAllorFind(predicate). Then it can't express includes, projections or paging, so filtering moves into memory, or the interface grows parameters until it's a weaker LINQ.
Generic writes undo what the change tracker gives you
Update(T) that calls DbSet<T>.Update throws that away. In a test with EF Core 10 on SQLite, it wrote every column of a loaded order back to the database, where saving through the change tracker sent only Status. Given an entity built by hand with just Id and Stock set, it wiped the product's Name and Price. And a repository whose AddAsync calls SaveChanges itself breaks the unit of work: an order saved by one repository stayed in the database when its line failed in the next.
What a repository does buy
The fix: name the queries, and let the context commit
using Microsoft.EntityFrameworkCore;public interface IRepository<T> where T : class{ IQueryable<T> Query(); void Update(T entity); // calls DbSet<T>.Update}// "Application" code, yet every query needs EF Core's extension methodspublic sealed class Checkout(IRepository<Order> orders, IUnitOfWork uow){ public async Task RunAsync(int orderId, CancellationToken ct) { var order = await orders.Query() .Include(o => o.Lines) .SingleAsync(o => o.Id == orderId, ct); order.Submit(); orders.Update(order); // marks every column as modified await uow.SaveChangesAsync(ct); }}namespace Shop.Application;// The use case owns its ports and names them after what it needspublic interface IOrderRepository{ Task<Order> GetForCheckoutAsync(int orderId, CancellationToken ct);}public interface IUnitOfWork{ Task SaveChangesAsync(CancellationToken ct);}// No EF Core here: a unit test stubs GetForCheckoutAsync directlypublic sealed class Checkout(IOrderRepository orders, IUnitOfWork uow){ public async Task RunAsync(int orderId, CancellationToken ct) { var order = await orders.GetForCheckoutAsync(orderId, ct); order.Submit(); await uow.SaveChangesAsync(ct); // writes only what changed }}using Microsoft.EntityFrameworkCore;using Shop.Application;namespace Shop.Infrastructure;public sealed class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options), IUnitOfWork{ public DbSet<Order> Orders => Set<Order>(); Task IUnitOfWork.SaveChangesAsync(CancellationToken ct) => SaveChangesAsync(ct);}public sealed class EfOrderRepository(ShopDb db) : IOrderRepository{ public Task<Order> GetForCheckoutAsync(int orderId, CancellationToken ct) => db.Orders.Include(o => o.Lines).SingleAsync(o => o.Id == orderId, ct);}UPDATE "Orders" SET "Status" and nothing else, and a unit test with a hand-written stub repository ran the use case with no database at all.
DbContext in handlers | |||
IRepository<T> and a unit-of-work class | IQueryable | DbContext | |
How to apply it in your project
Write the decision down Record whether Application code may use EF Core. Either answer works; leaving it implicit is what produces half-wrapped code. Make repositories specific One per aggregate root, with methods named after use cases, returning materialized results and never IQueryable.Commit once per use case Remove SaveChangesfrom repositories, and let theDbContextimplement yourIUnitOfWorkinstead of a wrapper class.Let reads go around Query handlers can project directly from the context with AsNoTracking, since reads don't need an aggregate's rules.
Key takeaways
Clean Architecture requires that business code not depend on EF Core; it doesn't require a generic repository. DbContextalready is a unit of work, andDbSet<T>already is a collection-like repository.A generic repository either leaks EF Core through IQueryableor hides the queries you need.Generic Updateand repositories that save on their own throw away the change tracker and the unit of work.When you want a seam, write a specific repository per aggregate and let the context commit once per use case.
📚 المصادر
Designing the infrastructure persistence layer — .NET Architecture Guides, Microsoft Learn Choosing a testing strategy — EF Core, Microsoft Learn DbContext Class — EF Core API reference, Microsoft Learn Repository — Martin Fowler, Catalog of Patterns of Enterprise Application Architecture The Clean Architecture — Robert C. Martin, The Clean Code Blog (2012)
التعليقات (0)