I've been learning about DDD and just wanted to make sure I understood something correctly. I've read in various places that aggregate roots properties should not directly reference entities from other aggregate roots. So let's say we have 2 aggregate roots: Student, and Course.
Originally, I would have designed my models like this:
public class Student
{
private int Id {get;}
private readonly List<Course> _courses = new();
public IReadOnlyCollection<Course> Courses => _courses;
public void Enroll(Course course)
{
_courses.Add(course);
}
}
public class Course
{
private int Id {get;}
private readonly List<Student> _students = new();
public IReadOnlyCollection<Student> Students => _students;
public void AddStudent(Student student)
{
_students.Add(student);
}
}
After learning about not referencing entities from other aggregates, I instead ended up with collection of ids instead:
public class Student
{
private int Id {get;}
private readonly List<int> _courses = new();
public IReadOnlyCollection<int> Courses => _courses;
public void Enroll(Course course)
{
_courses.Add(course.Id);
}
}
Is that correct? It feels somewhat weird and counter intuitive. I also don't like that now there is no typed guarantee that my collections elements will be of the expected type. I could mistakenly change my code to do _students.Add(course.Id)
and the error would be hard to catch. Any advice to avoid that?