开发手册 欢迎您!
软件开发者资料库

Entity Framework - 渴望加载

Entity Framework渴望加载 - 从概述,体系结构,环境设置,数据库设置,数据模型,DbContext,类型,关系,生命周期,代码优先方法,模型第一方法,数据库第一方法,DEV方法,数据库操作,并发开始学习实体框架,事务,视图,索引,存储过程,断开连接的实体,表值函数,本机SQL,枚举支持,异步查询,持久性,投影查询,命令记录,命令拦截,空间数据类型,继承,迁移,渴望,懒惰,显式加载,验证,跟踪更改,彩色实体,第一个示例,数据注释,Fluent API,种子数据库,代码优先迁移,多个DbContext,嵌套实体类型。

预先加载是一种过程,即对一种类型的实体的查询也会将相关实体作为查询的一部分加载.通过使用包含方法实现预先加载.

这意味着请求相关数据以及数据库的查询结果.只有一个与数据源建立的连接,在初始查询中返回的数据量较大.

例如,在查询学生时,急切加载他们的注册.学生及其注册将在一个查询中检索.

让我们看看下面的示例,其中使用预先加载从数据库中检索所有具有相应注册的学生.

class Program {   static void Main(string[] args) {      using (var context = new UniContextEntities()) {         // Load all students and related enrollments         var students = context.Students            .Include(s ⇒ s.Enrollments).ToList();         foreach (var student in students) {            string name = student.FirstMidName + " " + student.LastName;            Console.WriteLine("ID: {0}, Name: {1}", student.ID, name);            foreach (var enrollment in student.Enrollments) {               Console.WriteLine("Enrollment ID: {0}, Course ID: {1}",                   enrollment.EnrollmentID, enrollment.CourseID);            }         }         Console.ReadKey();      }   }}

编译并执行上述代码时,您将收到以下输出.

ID: 1, Name: Ali Alexander       Enrollment ID: 1, Course ID: 1050       Enrollment ID: 2, Course ID: 4022       Enrollment ID: 3, Course ID: 4041ID: 2, Name: Meredith Alonso       Enrollment ID: 4, Course ID: 1045       Enrollment ID: 5, Course ID: 3141       Enrollment ID: 6, Course ID: 2021ID: 3, Name: Arturo Anand       Enrollment ID: 7, Course ID: 1050ID: 4, Name: Gytis Barzdukas       Enrollment ID: 8, Course ID: 1050       Enrollment ID: 9, Course ID: 4022

以下是可以使用的一些其他形式的急切加载查询.

// Load one Student and its related enrollmentsvar student1 = context.Students   .Where(s ⇒ s.FirstMidName == "Ali")   .Include(s ⇒ s.Enrollments).FirstOrDefault();// Load all Students and related enrollments// using a string to specify the relationshipvar studentList = context.Students   .Include("Enrollments").ToList();// Load one Student and its related enrollments// using a string to specify the relationshipvar student = context.Students   .Where(s ⇒ s.FirstMidName == "Salman")   .Include("Enrollments").FirstOrDefault();

多个级别

也可能急切地加载多个级别的相关实体.以下查询显示学生,入学和课程的示例.

// Load all Students, all related enrollments, and all related coursesvar studentList = context.Students   .Include(s ⇒ s.Enrollments.Select(c ⇒ c.Course)).ToList();// Load all Students, all related enrollments, and all related courses// using a string to specify the relationshipsvar students = context.Students   .Include("Enrollments.Course").ToList();

我们建议您逐步执行上述示例,以便更好地理解.