DDD多层嵌套实体聚合根设计方案与仓储结构咨询
场景
说明:为提升可读性,我省略了部分代码(如公共/私有setter等)
现有代码结构如下:
class Configuration : RootAggregate { public string code; // other fields public List<Group> Groups; } class Group : Entity { public string code; // other fields public List<Characteristic> Characteristics; } class Characteristic : Entity { public string code; // other fields public List<Value> Values; } class Value : ValueObject { public string code; public string value; }
即存在一个包含多层嵌套实体的RootAggregate,层级关系为:
- 1个Configuration
- 最多10个Group
- 最多150个Characteristic
- 最多50个Value
- 最多150个Characteristic
- 最多10个Group
我尝试了两种方案:
方案一
将所有实体聚合在一起,以实体作为方法参数(而非原始类型)
弊端:仅更新单个Characteristic的Value时,需加载所有Group及关联Characteristic,存在性能与复杂度问题;仓储层需实现整Configuration更新方法,更新单个Value时需查询全量数据,更新后再遍历实体与数据库同步。
class Configuration : RootAggregate { public string code; // other fields public List<Group> Groups; public void AddGroup(Group group) public void UpdateGroup(Group group) public void RemoveGroup(string code) } class Group : Entity { public string code; // other fields public List<Characteristic> Characteristics; public void AddCharacteristic(Characteristic characteristic) public void UpdateCharacteristic(Characteristic characteristic) public void RemoveCharacteristic(string code) } class Characteristic : Entity { public string code; // other fields public List<Value> Values; public void CreateValue(string code, string value) public void UpdateValue(string code, string value) public void RemoveValue(string code) }
方案二
将Configuration与Group拆分(或拆分Configuration->Group、Characteristic->Value)
弊端:违反DDD原则,因为需在将Group添加至Configuration前先验证Group的code唯一性。
class Configuration : RootAggregate { public string code; // other fields } class Group : RootAggregate { public string ConfigurationId; public string code; // other fields public List<Characteristic> Characteristics; public void CreateCharacteristic (string code, <other fields>, IEnumerable<Value> values) public void UpdateCharacteristic (string code, <other fields>, IEnumerable<Value> values) public void DeleteCharacteristic (string code) } class Characteristic : Entity { public string code; // other fields public List<Value> Values; public SetValues(List<Value> values); } class Value : ValueObject { public string code; public string value; }
注:我已阅读过类似问题,但认为不适用于当前场景。
问题
- 针对DDD模式中包含N层嵌套实体的聚合根,应采用何种设计思路?
- 针对当前场景,最优解决方案是什么?
- 所选方案对应的IRepository结构应如何设计?
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

