我知道聚合根是唯一将由客户端加载的对象,聚合根中的对象的所有操作都由聚合根完成。按照同样的约定,应该为聚合根定义一个存储库接口,并且聚合根中的任何对象的任何持久性操作都应该通过与聚合根相对应的这个“聚集根存储库”来完成。这是否意味着只有聚合根对象应该被传递到与聚合根的子对象相关的操作的“聚合根存储库”?存储库模式中的聚合根
让我举个例子。
假设您有一个School对象和Student对象。由于学生不能没有学校存在的,(你可能会说,一个学生可能已经离开了学校,在这种情况下,他/她不再是一个学生),所以我们必须
class School
{
string SchoolName;
IList<Student> students;
}
class Student
{
string StudentName;
string Grade;
School mySchool;
}
学校是聚合根这里。现在假设我们想为持久性操作定义一个存储库。
以下哪项是正确的?
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
}
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.
}
在1)我们只暴露在界面的集合体。因此,任何实现ISchoolRepository的DAL都必须从School对象中获取Student对象来添加学生。 2)看起来更加明显,我可能看起来愚蠢的建议1),但在纯理论聚合根的概念,建议1)
第一种选择,但我会命名方法“保存”并让Repo决定它是一个添加还是更新 – MikeSW 2012-07-16 08:15:03