Yes. The Repository Pattern is a design pattern that puts a collection-like abstraction between the business logic and the data access code. Business code works with objects through a repository interface, without knowing how data is stored or retrieved. Example public interface IOrderRepository { Task<Order?> GetByIdAsync(int id, CancellationToken ct); Task<IReadOnlyList<Order>> GetRecentForCustomerAsync(int customerId, int take, CancellationToken ct); void Add(Order order); } public sealed class OrderRepository(AppDbContext db) : IOrderRepository { public Task<Order?> GetByIdAsync(int id, CancellationToken ct) => db.Orders.Include(o => o.Items).FirstOrDefaultAsync(o => o.Id == id, ct); public async Task<IReadOnlyList<Order>> GetRecentForCustomerAsync(int customerId, int take, CancellationToken ct) => await db.Orders.AsNoTracking() .Where(o => o.CustomerId == customerId) .OrderByDescending(o => o.CreatedAt).Take(take) .ToListAsync(ct); public void Add(Order order) => db.Orders.Add(order); } builder.Services.AddScoped<IOrderRepository, OrderRepository>(); It is often combined with the Unit of Work pattern, which commits changes from several repositories in one transaction (in EF Core, DbContext.SaveChanges plays that role). Benefits - Separation of concerns: business logic does not contain query details. - Testability: services can be tested with fake or mocked repositories. - Centralised, reusable queries and data rules (soft-delete filters, tenant filtering). - Ability to change data access technology behind the interface (in practice, this is rarer than expected). Criticism and trade-offs with EF Core - DbContext already implements the Repository and Unit of Work patterns (DbSet is a repository). A generic repository (IRepository<T> with GetAll, Add, Update, Delete) on top of EF Core often adds little and hides useful features: Include, projections, AsNoTracking and efficient queries. - Returning IQueryable from repositories leaks persistence details; returning everything as lists can cause performance problems. A balanced approach - Use specific repositories with meaningful methods (GetRecentForCustomerAsync), not generic CRUD wrappers, especially in domain-driven designs with aggregates. - For simple CRUD applications or read-heavy queries, using DbContext directly in application services or query handlers can be simpler. - For tests, consider running against a real database with Testcontainers rather than mocking every repository method.
Ravindra Wadile · · 0 likes