【发布时间】:2012-08-21 09:30:37
【问题描述】:
两个月前,我购买了 Scott Millet 的“专业 ASP.NET 设计模式”一书,因为我想学习如何使用设计模式构建分层的 Web 应用程序。我在自己的应用程序中使用了本书中的案例研究,所以一切都设置好了。
我的问题是我不确定我的聚合根。
我有一个可以创建集合的用户。用户可以将类别添加到集合中,并将关键字添加到类别中。在我的数据库中看起来像这样:
- Users
- PK: UserId
- Collections
- PK: CollectionId
- FK: UserId
- Categories
- PK: CategoryId
- FK: CollectionId
- Keywords
- PK: KeywordId
- FK: CategoryId
我不认为将用户作为集合的聚合根是合乎逻辑的,但是类别和关键字共同构成了一个集合。所以我让用户成为一个还没有孩子的聚合根,并收集一个聚合根。一个集合可以有多个类别,类别可以有多个关键字。所以当我想添加一个类别时,我会这样做:
public void CreateCategory(CreateCategoryRequest request)
{
Collection collection = _collectionRepository.FindCollection(request.IdentityToken, request.CollectionName);
Category category = new Category { Collection = collection, CategoryName = request.CategoryName };
ThrowExceptionIfCategoryIsInvalid(category);
collection.AddCategory(category);
_collectionRepository.Add(collection);
_uow.Commit();
}
效果很好,但是当我想添加关键字时,我首先需要获取集合,然后获取可以添加关键字的类别,然后提交集合:
public void CreateKeyword(CreateKeywordRequest request)
{
Collection collection = _collectionRepository.FindCollection(request.IdentityToken, request.CollectionName);
Category category = collection.Categories.Where(c => c.CategoryName == request.CategoryName).FirstOrDefault();
Keyword keyword = new Keyword { Category = category, KeywordName = request.KeywordName, Description = request.KeywordDescription };
category.AddKeyword(keyword);
_collectionRepository.Add(collection);
_uow.Commit();
}
这只是感觉不对(是吗?)是什么让我相信我应该将类别作为关键字的总根。但这提出了另一个问题:我有一个集合聚合,它像我在第一个代码示例中所做的那样创建一个类别聚合,这仍然有效吗?示例:collection.Add(category);
【问题讨论】:
-
在这种情况下,一个简单的经验法则是考虑“在集合之外有一个类别是否有意义?”如果没有,将类别作为单独的根并没有多大意义。
-
我想到了这一点,因为我在一个页面上显示集合,在另一个页面上显示带有关键字的类别。但是即使它不是聚合根,通过类别对象添加关键字仍然有意义吗?
-
然后考虑这个;该类别在集合之外具有身份是否有意义?即,如果两个用户添加同名的类别,它们是集合本地的还是用户之间共享的?
-
它们在集合中是本地的。
标签: c# asp.net domain-driven-design