How to eagerly load a many to many relationship with the entity framework code first?

雨燕双飞 提交于 2019-12-01 04:54:07

问题


I'll give the most basic example that I can think of for the purpose of clarity.

Lets say that I have two entities of the following form:

public class Student
{
    public int Id {get;set}
    public string FullName {get;set;}
    public virtual ICollection<Course> Courses {get;set;}
}

public class Courses
{
    public int Id {get;set;}
    public string FullName {get;set;}
    public virtual ICollection<Student> Students {get;set;}
}

Those two entities map to three tables, the third one being a table for the joins.

When I query the Students like this

var allStudents = context.Students;

and then traverse the results to display a list of students and their courses like this

foreach (var student in allStudents) 
{
    display(student.FullName);
    foreach (var course in student.Courses) 
    {
        display(course.FullName);
    }
}

I get a Course query for each Student that the first query returned.

How do I tell the entity framework to eagerly load the courses into the students with just one query?


回答1:


You want an Include() query to indicate that you want to eagerly load the related Course entities:

var allStudents = context.Students.Include( s => s.Courses);

Also make sure you have a

using System.Data.Entity;

in your code file so you can use the strongly typed Include() extension method.



来源:https://stackoverflow.com/questions/5851169/how-to-eagerly-load-a-many-to-many-relationship-with-the-entity-framework-code-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!