2020-05-24 - Linq查询2

加载相关数据

预先加载

  • 表示从数据库中加载关联数据,作为初始查询的一部分。
    a. 使用 Include 方法来指定要包含在查询结果中的关联数据
    b. 使用 ThenInclude 方法可以依循关系包含多个层级的关联数据
    c. 包含中可以使用筛选 ( Where、OrderBy、OrderByDescending、ThenBy、ThenByDescending、Skip 和 Take )

    只能对每个包含的导航执行一组唯一的筛选器操作

var blogs = context.Blogs
        .Include(blog => blog.Posts
                                  .Where(post => post.BlogId == 1)
                                  .OrderByDescending(post => post.Title)
                                  .Take(5)
        )
            .ThenInclude(post => post.Author)
                .ThenInclude(author => author.Photo)
        .Include(blog => blog.Owner)
            .ThenInclude(owner => owner.Photo)
         .Include(blog => blog.Posts) // 这儿不能再次使用 where 筛选器操作了
        .ToList();

d. 可以使用 Include 和 ThenInclude 包括来自仅在派生类型上定义的导航的相关数据。
即因为子类通过 鉴别器列 放在父类表中, 查询父表(这时肯定查询出子表)时,可以查询到子类表关联的数据

public class Person
{
    public string Name { get; set; }
}
public class Student : Person
{
    public School School { get; set; }
}
public class School
{
    public int Id { get; set; }
    public List<Student> Students { get; set; }
}
  1. 使用强制转换
  2. 使用 as 运算符
  3. 使用 include
  • 显式加载表示稍后从数据库中显式加载关联数据。

  • 延迟加载表示在访问导航属性时,从数据库中以透明方式加载关联数据。

显式加载

通过 DbContext.Entry(...) API 显式加载导航属性

var blog = context.Blogs.Single(b => b.BlogId == 1);
context.Entry(blog).Collection(b => b.Posts).Load();
var goodPosts = context.Entry(blog).Collection(b => b.Posts).Query().Where(p => p.Rating > 3).ToList();

延迟加载

使用延迟加载的最简单方式是通过安装 Microsoft.EntityFrameworkCore.Proxies 包,
并通过配置 DbContextOption 调用 UseLazyLoadingProxies 扩展方法来启用该包
会为可重写的任何导航属性(即,必须是 virtual 且在可被继承的类上)启用延迟加载

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。