Frip
Frip

Reputation: 884

How to get data from many-to-many relationship builded by Entity Framework Core?

I made many-to-many relationship from this tutorial

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}

public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

How i can take Courses list by StudentID?

How it convert to IQueryable<Student> (need for asp.net)?

Thanks.

Upvotes: 0

Views: 3415

Answers (1)

VeithB&#252;rgerhoff
VeithB&#252;rgerhoff

Reputation: 68

If all you want to do is get all the courses that a student is taking there are multiple ways to go about this. I am guessing you have a DbSet<StudentCourse> StudentCourses entry in your database context. You could simply call context.StudentCourses.Include(x => x.Student).Where(entry => entry.CourseId == theIdYouWant).Select(entry => entry.Student).

Note the .Include() which tells Entity Framework to "join" the student table with the StudentCourse table so you will get the actual student entities instead of just the ids (if you left the include out it is very likely the student property would just be set to null)

Upvotes: 3

Related Questions