多级预先加载

多级预先加载

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

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int Rating { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
    public Author Author { get; set; }
}

public class Author
{
    public int aid { get; set; }
    public List<Post> Posts { get; set; }
    public Photo Photo { get; set; }
}

public class Photo
{
    public Author Author { get; set; }
}Code language: JavaScript (javascript)

可通过链式调用 ThenInclude,进一步包含更深级别的关联数据。

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)
        .ToList();
}Code language: JavaScript (javascript)
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)
                .ThenInclude(author => author.Photo)
        .ToList();
}Code language: JavaScript (javascript)

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

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();
}Code language: JavaScript (javascript)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注