Im having a problem with the design of my Models. The application has Modules (I.e. University modules) which are taught by one or many Lecturers, Lecturers can also teach one or many Modules, therefore in terms of database design there is a Many-to-many relationship between Modules and Lecturers, hence in my database this relationship will be represented by an addition table that has Module_id and Lecturer_id as a composite key to achieve this I included a list of lecturers in the module class with the virtual modifier and visa versa, as seen below
public class Module
{
public int id { get; set; }
public string name { get; set; }
public Department department { get; set; }
public string code { get; set; }
public virtual List<Lecturer> lecturers { get; set; }
...
}
And the lecturer class:
public class Lecturer
{
public int id { get; set; }
public string name { get; set; }
public virtual List<Module> modules { get; set; }
...
}
My first question is, is this the best way to implement this situation in the Models? It seems to work ok, however this means that Modules have Lecturers which teach Modules which then Taught by the Lecturers… and so on, and hence seems very inefficient and not optimal. It also means that I cannot simply return, for example a Module as a JSON object to the browser because of this loop.
Finally, if this is the correct implementation is there a way using LINQ to query for a Module and then return a limited Module that has Lecturers but then the Lectures are restricted and do not have modules associated with them? At the moment I am using the following statement?
Module module = dbContext.Modules.Where(r => r.id == id).Single();
Personally, when dealing with many-to-many relationships, I like to make the relationship table a concrete part of my model. That is, I would have a
LecturerModuletable that bothLecturerandModulereference. In a many-to-many relationship, the relationship is a thing. This makes the most architectural sense for me and makes models so much easier to work with rather than trying to hide the relationship in some sort of complex looped tree.