DDD仓储模式:是否应通过聚合根CRUD子聚合?
Absolutely spot-on observation—this is a fundamental DDD principle that’s crucial to get right, and it sounds like you’ve been digging into solid resources to reinforce it. Every credible DDD resource out there will hammer home that Repositories should only be built for Aggregate Root entities, and I couldn’t agree more.
Let’s use your Product and Variant example to make this crystal clear:
Productis the Aggregate Root here, so the only Repository you need in this context is aProductRepository.- Any CRUD operations on
Variantshould happen through the Product aggregate (via theProductRepository), not through a separateVariantRepository. The reason is simple: a Variant has no meaningful existence on its own—it’s inherently tied to a Product.
This approach isn’t just arbitrary; it serves core DDD goals:
- Protects aggregate integrity: By only modifying Variants through their parent Product, you ensure all business rules around Variant creation, updates, or deletion are enforced directly in the Product entity. No orphaned Variants floating around, no invalid state changes that bypass domain logic.
- Keeps your codebase clean: You avoid cluttering your data layer with unnecessary Repositories for child entities, keeping things focused on the aggregate boundaries that matter to the business.
- Aligns with domain language: The business doesn’t talk about "Variants" in isolation—they talk about "Products with their Variants." Building Repositories around aggregates keeps your code aligned with how stakeholders think about the problem.
Here’s a quick code snippet to illustrate the practical flow (using C# as an example):
// Load the full Product aggregate via its Repository var product = await _productRepository.GetByIdAsync(targetProductId); // Modify the Variant through the Product's domain methods product.UpdateVariant(targetVariantId, newVariantDetails); // Save the entire aggregate back—no separate Variant save needed await _productRepository.SaveAsync(product);
This pattern ensures every change to a Variant is governed by the Product’s domain rules, which is exactly what DDD is designed to achieve.
内容的提问来源于stack exchange,提问作者Amr Elgarhy

