c# - 聚合根和存储库

标签 c# design-patterns domain-driven-design ddd-repositories aggregateroot

我目前正在尝试发现聚合根 背后的想法及其与存储库的关系。

给定以下域实体:

public class Country {

    public string Name { get; set; }
    public ICollection<City> Cities { get; set; }

}

public class City {

    public string Name { get; set; }

}

我猜我正确地将Country 识别为City聚合根,因为在我的域中,不应该有任何城市是不在一个国家内。应该只能通过一个国家将一个新城市添加到数据存储中,如果一个国家被删除,里面的每个城市也应该被删除。

现在,这样的国家资料库会是什么样子? Country Aggregate Root 是什么样子的?域内是否有 CityRepository(即使没有相关国家/地区,我也可以将城市添加到数据库中!)? Country 内部是否有一个CountryRepository(国家需要以某种方式填充它的城市?或者这是存储库的工作?)

最佳答案

我想你已经掌握了窍门。在您描述的情况下:

since in my domain, there shouldn't be any cities that are not located within a country. It should be only possible to add a new city to the data storage via a country and if a country get's deleted, every city inside should be removed too

你是对的,国家是聚合根。你的国家实体代码是聚合根,是正确的!你不会想要一个城市 repo 。根据相关的值(value)对象(在本例中为城市)或实体,您的国家/地区 repo 并没有真正改变,因此在这种情况下,您的基本 crud api 如下所示:

public class CountryRepo {
    public Country GetCountry(String name);
    public Country SaveCourntry(Country country);
    public void DeleteCourntry(Country country);
    ...etc...
}

关于您的最后一个问题:

And is there a CountryRepository inside the Country (somehow the country needs to populate it's cities? Or is this the job of a repository?)

您的存储库将负责事件(处理您的实体)。填充城市将通过维护集合在实体中完成。您可以在您的 Country 实体上创建一个方法来添加城市:

public void AddCity(City city)
{
    this.Cities.Add(city);
}

remove 类似,然后你使用你的 repo 来保存国家,它应该负责保留相关的城市集合。

关于c# - 聚合根和存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567474/

相关文章:

c# - 如何通过域对象和服务中的验证与 UI 层中的验证保持 DRY

c# - 剪刀石头布的胜率百分比不起作用?

php - 你知道一本关于构建代码的好书/网站吗(PHP/Web 编程)

design-patterns - 如何可靠地处理队列?

design-patterns - 必须加入 fork 节点吗? UML 状态图

service - DDD Repo - repo.findByChildId(id) AND repo.transferChild(to, from, child)

domain-driven-design - Saga,存储聚合状态的位置

c# - 如何解决 IronPython Compile() 问题?

c# - MongoDB .NET 流畅聚合查询

c# - 如何以编程方式链接 Azure DevOps 中的分支和工作项