SOLID & Design Patterns Interview Question #80

Should every entity have its own repository in DDD?

DDD Boundaries, Resilience, Caching & Practical ASP.NET Core Design Mid-Level Intermediate

Quick Interview Answer

No. In Domain-Driven Design, repositories are commonly associated with aggregate roots rather than every entity or database table. Internal entities should normally be loaded and modified through their aggregate root.

Detailed Explanation

No. In Domain-Driven Design, repositories are commonly associated with aggregate roots rather than every entity or database table. Internal entities should normally be loaded and modified through their aggregate root.

Creating a repository for every table can expose aggregate internals and weaken consistency boundaries. Repository design should follow the domain model rather than mirror the relational schema.

Code Example

public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(Guid id);
    Task AddAsync(Order order);
}

// OrderItem is modified through Order,
// not through a separate OrderItemRepository.