You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DDD仓储模式:是否应通过聚合根CRUD子聚合?

Repository Design in DDD: Stick to Aggregate Roots Only

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:

  • Product is the Aggregate Root here, so the only Repository you need in this context is a ProductRepository.
  • Any CRUD operations on Variant should happen through the Product aggregate (via the ProductRepository), not through a separate VariantRepository. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:59