I have a .net solution (with Entity Framework, using the CodeFirst approach) about the administration of a university. The architecture of the project is like this:
- DataAccess (DbContext and Generic Repository)
- Entities (code first classes)
- Services (services classes)
- Web (an MVC project, not important for the explanation)
For making the question easier, i'll only talk about two classes from my domain (on the Entities layer):
- Course
- Student
The course can have many students. And the objective of the solution, is to add students to the courses (with some validation in the middle).
Course.cs
public class Course
{
[Key]
public int IdCourse { get; protected set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; protected set; }
public void AddStudent(Student student)
{
// Some Validation
Students.Add(student);
}
}
As you can see, the class has a property for adding students to the course. The situation is that the validation is growing and now is very complex, and it needs to make some queries to the database and more... So the course have a lot of responsibilities!
So i thought, that i needed a service for handling the "Adding" and making all the validation and take this reponsibility away from the Course class. The problem is that, as the Students Collection is a private member from Course, i can't add students to courses from the Service class.
Another way i thought to solve the problem, is adding the related entity (the student) to the context (from the service), but it would break my repository (because i would have to make the DbContext public). And if i use the DbContext from the Service class directly, the repository has no point, hasn't it?
So, how should i design that? or what should i do to solve the problem? Any suggestion would be very well received too!
Thanks!