dev*_*yst 5 repository aggregateroot repository-pattern
我知道聚合根是唯一将由客户端加载的对象,聚合根内对象的所有操作都由聚合根完成。按照相同的约定,应该为聚合根定义一个存储库接口,并且聚合根内任何对象的任何持久性操作都应该由与聚合根对应的“聚合根存储库”完成。这是否意味着只有 Aggregate Root 对象应该传递到“Aggregate Root Repository”以进行与 Aggregate Root 的子对象相关的操作?
让我举个例子吧。
假设您有一个 School 对象和 Student 对象。由于学生不能没有学校,(你可能会说学生可能已经离开学校,在这种情况下他/她不再是学生),所以我们有
class School
{
string SchoolName;
IList<Student> students;
}
class Student
{
string StudentName;
string Grade;
School mySchool;
}
Run Code Online (Sandbox Code Playgroud)
学校是这里的聚合根。现在假设我们要为持久性操作定义一个存储库。
下面哪个是正确的?
1)
interface ISchoolRepository
{
void AddSchool(School entity);
void AddStudent(School entity); //Create a School entity with only the student(s) to be added to the School as the "students" attribute
}
Run Code Online (Sandbox Code Playgroud)
2)
interface ISchoolRepository
{
void AddSchool(School entity);
void AddStudent(Student entity); //Create a Student entity. The Student entity contains reference of School entity in the "mySchool" attribute.
}
Run Code Online (Sandbox Code Playgroud)
在 1) 中,我们只在接口中公开聚合。因此,任何实现 ISchoolRepository 的 DAL 都必须从 School 对象中获取 Student 对象才能添加学生。2) 看起来更明显,我可能看起来很愚蠢,建议 1) 但纯理论中的总根概念会建议 1)
我在这里发现了一个类似的问题,我应该如何将对象添加到由聚合根维护的集合中
合并上述链接中的两个答案,正确的方法是
interface ISchoolRepository
{
void AddSchool(School entity);
void AddStudent(Student entity); //Create a Student entity. The Student entity contains reference of School entity in the "mySchool" attribute.
}
Run Code Online (Sandbox Code Playgroud)
或者更严格地说
interface ISchoolRepository
{
void AddSchool(School entity);
void AddStudent(string StudentName, string Grade); //without exposing Student type
}
Run Code Online (Sandbox Code Playgroud)