Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID from association using Entity Framework

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: DB Schema

I used this db to create an Entity model in Visual Studio: VS Schema

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.

like image 662
JSS Avatar asked Dec 19 '25 05:12

JSS


1 Answers

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.

like image 178
Slauma Avatar answered Dec 21 '25 21:12

Slauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!