我目前正在尝试发现聚合根 背后的想法及其与存储库的关系。
给定以下域实体:
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/