显示加载
在这里,您将学习如何显式地加载实体中的导航实体。显式加载在EF 6和EF Core中是有效的。
即使禁用了延迟加载(在EF 6中),仍然可以延迟加载相关实体,但必须通过显式调用来完成。使用Load()方法显式加载相关实体。考虑下面的例子。
using (var context = new SchoolContext())
{
var student = context.Students
.Where(s => s.FirstName == "Bill")
.FirstOrDefault<Student>();
context.Entry(student).Reference(s => s.StudentAddress).Load(); // 显示加载StudentAddress
context.Entry(student).Collection(s => s.StudentCourses).Load(); // 显示加载Courses collection
}
在上面的例子中,context.Entry(student).Reference(s => s.StudentAddress).Load()加载StudentAddress实体。Reference()方法用于获取指定引用导航属性的对象,Load()方法显式加载它。
同样,context.Entry(student).Collection(s => s.Courses).Load()加载Student实体的集合导航属性Courses。Collection()方法获取一个表示集合导航属性的对象。
Load()方法在数据库中执行SQL查询,以获取数据并在内存中填充指定的引用或集合属性,如下所示。
Query()
您还可以编写LINQ-to-Entities查询,以便在加载之前过滤相关数据。Query()方法使我们能够为相关实体编写进一步的LINQ查询,以过滤出相关数据。
using (var context = new SchoolContext())
{
var student = context.Students
.Where(s => s.FirstName == "Bill")
.FirstOrDefault<Student>();
context.Entry(student)
.Collection(s => s.StudentCourses)
.Query()
.Where(sc => sc.CourseName == "Maths")
.FirstOrDefault();
}
在上面的例子中,.Collection(s => s.StudentCourses).Query()允许我们为StudentCourses实体编写进一步的查询。
参考
https://www.entityframeworktutorial.net/
https://msdn.microsoft.com/