使用 Include 和 ThenInclude 可高效加载 EF Core 中的关联数据。1. 用 Include 加载直接关联数据,如博客及其文章;2. 用 ThenInclude 加载多级关联,如文章的作者;3. 多个独立导航属性可多次调用 Include;4. 注意避免过度加载,优先使用强类型方法以提升性能与安全。

在使用 EF Core 进行数据查询时,经常会遇到需要加载相关联的数据(导航属性)的场景。EF Core 提供了多种方式来“包含”这些关联数据,最常用的是 Include 和 ThenInclude 方法。下面介绍如何正确使用它们来加载相关数据。
当你有一个实体包含导航属性(例如,一个博客有多个文章),你可以使用 Include 来显式加载这些关联数据。
示例:假设你有两个类:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
要查询所有博客并包含其文章,可以这样写:
var blogs = context.Blogs
.Include(b => b.Posts)
.ToList();
这会生成一条 SQL 查询(或使用 JOIN),将 Blogs 和 Posts 一起加载,避免了 N+1 查询问题。
如果关联属性还有自己的导航属性,可以使用 ThenInclude 继续向下加载。
示例:假设 Post 还有一个作者信息:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
}
修改 Post 类:
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public int BlogId { get; set; }
public int AuthorId { get; set; }
public Blog Blog { get; set; }
public Author Author { get; set; }
}
现在你想加载博客、博客的文章,以及每篇文章的作者:
var blogs = context.Blogs
.Include(b => b.Posts)
.ThenInclude(p => p.Author)
.ToList();
这样就能一次性加载三层关联数据。
如果一个实体有多个独立的导航属性,可以多次调用 Include。
示例:比如 Blog 还有一个“管理员”属性:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public int AdminId { get; set; }
public Admin Admin { get; set; }
public List<Post> Posts { get; set; }
}
你可以同时加载 Posts 和 Admin:
var blogs = context.Blogs
.Include(b => b.Posts)
.Include(b => b.Admin)
.ToList();
使用 Include 时要注意以下几点:
.Include("Posts")),但不推荐,因为缺乏编译时检查。基本上就这些。合理使用 Include 和 ThenInclude,能让你高效地加载关联数据,提升应用性能。
以上就是C#中如何使用EF Core的查询包含?加载相关数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号