EF Core中数据的预先加载

预先加载
可以使用 Include 方法来指定要包含在查询结果中的关联数据

using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ToList();
}

 

可以在单个查询中包含多个关系的关联数据。

C#
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .Include(blog => blog.Owner)
        .ToList();
}

包含多个层级
使用 ThenInclude 方法可以依循关系包含多个层级的关联数据。 以下示例加载了所有博客、其相关文章及每篇文章的作者。

C#

复制
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ToList();
}

 

可以将对来自多个级别和多个根的关联数据的所有调用合并到同一查询中。

C#

复制
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.Include(blog => blog.Owner)
.ThenInclude(owner => owner.Photo)
.ToList();
}

 

经过筛选的包含

在应用包含功能来加载相关数据时,可对已包含的集合导航应用某些可枚举的操作,这样就可对结果进行筛选和排序。

支持的操作包括:WhereOrderByOrderByDescendingThenByThenByDescendingSkip 和 Take

应对传递到 Include 方法的 Lambda 中的集合导航应用这类操作,如下例所示:

C#
using (var context = new BloggingContext())
{
    var filteredBlogs = context.Blogs
        .Include(
            blog => blog.Posts
                .Where(post => post.BlogId == 1)
                .OrderByDescending(post => post.Title)
                .Take(5))
        .ToList();
}

只能对每个包含的导航执行一组唯一的筛选器操作。 如果为某个给定的集合导航应用了多个包含操作(下例中为 blog.Posts),则只能对其中一个导航指定筛选器操作:

C#
using (var context = new BloggingContext())
{
    var filteredBlogs = context.Blogs
        .Include(blog => blog.Posts.Where(post => post.BlogId == 1))
        .ThenInclude(post => post.Author)
        .Include(blog => blog.Posts)
        .ThenInclude(post => post.Tags.OrderBy(postTag => postTag.TagId).Skip(3))
        .ToList();
}
 
posted @ 2024-03-27 21:28  一个人走在路上  阅读(19)  评论(0编辑  收藏  举报