ASP.NET Core Web API Interview Question #106
What is the repository pattern, and is it always required with EF Core?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
A repository abstracts data-access operations behind an application-specific interface. It can be useful when the domain requires a meaningful persistence abstraction or when multiple data sources must be coordinated.
Detailed Explanation
A repository abstracts data-access operations behind an application-specific interface. It can be useful when the domain requires a meaningful persistence abstraction or when multiple data sources must be coordinated.
EF Core's DbContext and DbSet already provide unit-of-work and repository-like capabilities, so adding generic repositories purely as wrappers can create unnecessary indirection. Use repositories when they add a real architectural boundary rather than by default.
Code Example
public interface IOrderRepository
{
Task<Order?> GetAsync(
int id,
CancellationToken token);
Task AddAsync(
Order order,
CancellationToken token);
}