如何热切地加载与实体框架代码的多对多关系首先? [英] How to eagerly load a many to many relationship with the entity framework code first?
问题描述
假设我有两个实体,它们的形式如下:
/ p>
public class Student
{
public int Id {get; set}
public string FullName {get; set;}
public virtual ICollection< Course>课程{get; set;}
}
public class课程
{
public int Id {get; set;}
public string FullName {get ; set;}
public virtual ICollection< Student>学生{get; set;}
}
这两个实体映射到三个表
当我像这样查询学生
时code> var allStudents = context.Students;
,然后遍历结果以显示学生及其课程列表,例如
foreach(var student in allStudents)
{
display(student.FullName);
foreach(var course in student.Courses)
{
display(course.FullName);
}
}
我获得每个学生的课程查询
如何告诉实体框架只用一个查询来热心地将课程加载到学生中?
var allStudents = context.Students.Include(s => s.Courses) ;
同时确保您有
使用System.Data.Entity;
,因此您可以使用强类型 Include / code>扩展方法。
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?
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.
这篇关于如何热切地加载与实体框架代码的多对多关系首先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!