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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With