الانتقال إلى المحتوى
.NETClean Architecture· 8 دقائق للقراءة

Do You Need a Repository on Top of EF Core? The Honest Trade-offs

Clean Architecture asks that inner code not depend on EF Core. A generic repository and unit of work rarely deliver that; a specific repository per aggregate, or the DbContext itself, usually does.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A new service starts from a popular template: Domain, Application, Infrastructure and Api projects, a 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

The belief: Clean Architecture requires wrapping EF Core in a generic repository and a unit of work. The Application layer must never see a DbContext, and the wrapper is what makes it testable and lets you swap the ORM later.

The goals behind it are real. Business rules shouldn't depend on a persistence framework, and fast tests that don't need a database are valuable. Repository and Unit of Work are well-known patterns from Martin Fowler's catalog, Domain-Driven Design leans on repositories, and Microsoft's microservices guide uses them. Popular templates ship the generic version, so it looks like part of the architecture. The half-truth is that the goal is right and the generic shape is the problem.

What actually happens

DbContext already is both patterns

EF Core's API reference says it directly: 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

The says inner code must not name anything from an outer layer, and a repository interface helps only if EF Core stays behind it. A generic repository fails in one of two ways:

  • It returns IQueryable<T>. Callers need Include, AsNoTracking and SingleAsync, all extension methods from EF Core, so the dependency comes straight back. Microsoft's testing guide adds that a repository exposing IQueryable can't be stubbed reliably; in a test, a list's AsQueryable() threw the IAsyncEnumerable error above.
  • It returns lists from GetAll or Find(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

The change tracker knows which properties changed. A generic 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

Microsoft's guide describes the version that pays off: one repository per , never one per table, with the interface in the domain layer and the implementation in infrastructure. Queries can go around it, as in CQRS, because they don't change state. The testing guide calls a repository layer the only approach that allows comprehensive, reliable stubbing of data access, at a significant cost, since every testable query becomes a method and still needs a test against the real database. The architecture guide is just as clear that repositories aren't mandatory.

The fix: name the queries, and let the context commit

C# Checkout.cs
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);    }}

Infrastructure implements both ports without re-implementing anything. The context itself is the unit of work:

C# EfOrderRepository.cs
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);}

In the test, this version sent 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.

OptionEF Core in the Application layerUnit tests without a databaseCost
DbContext in handlersYes, by decisionNo: test against the databaseLowest; full EF Core power
Generic IRepository<T> and a unit-of-work classUsually, through IQueryableOnly for trivial queriesTwo layers that re-wrap DbContext
A specific repository per aggregateNoYes, by stubbing its methodsA method per query, plus integration tests
Reads that bypass the repositoryIn query handlers onlyTest queries against the databaseTwo paths for one aggregate's data

How to apply it in your project

  1. Write the decision downRecord whether Application code may use EF Core. Either answer works; leaving it implicit is what produces half-wrapped code.
  2. Make repositories specificOne per aggregate root, with methods named after use cases, returning materialized results and never IQueryable.
  3. Commit once per use caseRemove SaveChanges from repositories, and let the DbContext implement your IUnitOfWork instead of a wrapper class.
  4. Let reads go aroundQuery 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.
  • DbContext already is a unit of work, and DbSet<T> already is a collection-like repository.
  • A generic repository either leaks EF Core through IQueryable or hides the queries you need.
  • Generic Update and 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.

📚 المصادر

  1. Designing the infrastructure persistence layer — .NET Architecture Guides, Microsoft Learn
  2. Choosing a testing strategy — EF Core, Microsoft Learn
  3. DbContext Class — EF Core API reference, Microsoft Learn
  4. Repository — Martin Fowler, Catalog of Patterns of Enterprise Application Architecture
  5. The Clean Architecture — Robert C. Martin, The Clean Code Blog (2012)

التعليقات (0)