Many-to-many Relationship Query with LINQ to Entities

0

I've created a database that has two tables called Teachers and Courses . A teacher can teach in many courses and a course can have many teachers. I've created the Teacher Courses table to match both. When using the Entity Framework wizard to do the mapping, it did not generate the entity class from the TeacherCurrents table. Instead, both classes have HashSets that represent their lists of Teachers and Courses. The problem is that in the application, when I try to enroll a Teacher in a Course or enroll a Course for a Teacher, it may be that the Teacher is already related to the Course and in this case, an exception is thrown. The question is: how can I recover all Teachers from a Course or vice versa using LINQ to Entities? If I can get them back, I can handle the problem of ambiguous inscriptions. Thank you in advance.

    
asked by anonymous 09.12.2016 / 23:54

1 answer

0

Do the search and bring in a Curso of code 1, already in the relation will come all Professores related:

Cursos curso = db.Cursos.Find(1);

// contem a lista de professores do curso 1
ICollection<Professores> profLista = curso.Professores.ToList(); 

can also do the opposite Professores of code 1 brings the Cursos related:

Professores prof = db.Professores.Find(1);

// contem a lista de cursos do professor 1
ICollection<Cursos> curList = prof.Cursos.ToList();

References:

09.12.2016 / 23:56