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?
IsValid()method or write a constructor that takes parameters and automatically constructs a valid domain object. – Robert Harvey Oct 05 '17 at 20:47IRepositoryinterface (which already provides a substantial amount of decoupling), I'm OK with injecting an implementation into the domain object and letting the domain object sort out all of the business logic specifically pertaining to that domain object, if that is a convenient way to do it. – Robert Harvey Oct 06 '17 at 15:02