Get ID from association using Entity Framework
associations, c#, entity-framework, linq
Solution
You should be able to get the course IDs by using:
var studentsCourseIDs = (from s in school.Students
where s.ID == selectedStudentId
select s.Courses.Select(c => c.ID))
.Single();
Alternatively you start from the `Courses` set:
var studentsCourseIDs = (from c in school.Courses
where c.Students.Any(s => s.ID == selectedStudentId)
select c.ID)
.ToList();
Don't use the `AsEnumerable()` in your example because it will load the whole students table into memory before the `where` clause and the selection is applied.
Problem
I have this small application that I'm building as an exercise to learn the basics of the Entity Framework. It uses a MySQL db with 3 tables: Courses, Students and Students_has_Courses: I used this db to create an Entity model in Visual Studio: It's working fine. I can bind a table with my datagridview, modify data and press a button to save the changes. But as you see, the Students_has_Courses is an association (this is pretty new to me). And now my question: I need every Course ID for a specified student ID (to know which courses a student is taking). I thought this LINQ query would be fine: ``` var query = from s in school.Students.AsEnumerable() where s.ID == selectedStudentId select s.Courses; ``` But I can't really seem to extract the Course ID's from this EntityCollection ? I used a `foreach(var course in query)` but I'm really stuck here.