Suppose I have the following class:
public class Course {
// data
public string Name { get; }
public List<Student> Students {get;}
//...
// logic
public int AverageGrade() {/* do something*/}
public bool ReachedMaxStudents(){/* do something */}
}
I have some operations that interact with the database such as inserting a student to a class (should be done in the database as well.) What is the best approach to this?
First approach: developer has to know the course Id and pass it to repository.
public class CourseRepository : ICourseRepository{
public void InsertStudent(int CourseId, StudentDto student){
/* do something */
}
}
Second approach: embed repository inside the domain object:
public class Course {
private ICourseRepository _repo;
// data
public string Name { get; }
public List<Student> Students {get;}
//...
// logic
public int AverageGrade() {/* do something*/}
public bool ReachedMaxStudents(){/* do something */}
public void AddStudent(Student student){
StudentDto s = /* map Student to Studentdto */
_repo.Insert(s);
}
}
What are the pros and cons to each approach and which one is preferred?