⚙️ C# / .NET Intermediate

What is the Repository pattern in C#?

Answer

The Repository pattern abstracts data access logic behind an interface, decoupling the domain layer from data persistence concerns. The repository acts as a collection-like interface for accessing domain objects. Example: public interface IUserRepository { Task<User> GetByIdAsync(int id); Task<IEnumerable<User>> GetAllAsync(); Task AddAsync(User user); Task UpdateAsync(User user); Task DeleteAsync(int id); }. Implementation: public class EfUserRepository : IUserRepository { private readonly AppDbContext _ctx; ... }. Benefits: (1) Testability — inject a mock repository in unit tests. (2) Swap data sources without changing domain logic. (3) Centralized query logic. Debate: EF Core's DbContext is itself a Unit of Work + Repository, making an additional repository layer sometimes redundant (the "generic repository antipattern"). Use repositories when: testing requires it, data source might change, or query complexity benefits from centralization. Keep repositories thin — business logic belongs in domain/service layers.