显式加载是指先查询主实体,再通过EntityEntry的Collection或Reference方法调用Load/LoadAsync手动加载导航属性,适用于按需动态加载关联数据的场景。

在使用 EF Core 时,显式加载(Explicit Loading)是一种按需加载关联数据的方式。它允许你在主实体已经加载后,根据需要手动加载其导航属性的数据,而不是在查询主实体时就一次性加载所有相关数据。
什么是显式加载?
显式加载指的是:先查询出主实体,之后再调用 EntityEntry.Collection 或 EntityEntry.Reference 方法配合 Load() 或 LoadAsync() 来加载导航属性的数据。
这种方式适合在你不确定是否需要关联数据、或想根据业务逻辑动态决定是否加载的情况下使用。
如何使用显式加载?
假设有一个 Blog 实体,它包含多个 Post:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection 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; }
}
现在你想先查出某个博客,然后根据用户操作再决定是否加载它的文章列表。
using (var context = new AppDbContext())
{
// 先只查询 Blog,不包含 Posts
var blog = context.Blogs.FirstOrDefault(b => b.Id == 1);
if (blog != null)
{
// 显式加载 Posts 导航属性
context.Entry(blog)
.Collection(b => b.Posts)
.Load();
}
// 此时 blog.Posts 已被填充
foreach (var post in blog.Posts)
{
Console.WriteLine(post.Title);
}
}
如果是单个引用导航属性(如反向导航),使用 Reference:
context.Entry(post)
.Reference(p => p.Blog)
.Load();
异步方式加载
推荐在异步方法中使用异步加载,避免阻塞线程:
await context.Entry(blog)
.Collection(b => b.Posts)
.LoadAsync();
await context.Entry(post)
.Reference(p => p.Blog)
.LoadAsync();
添加过滤条件(仅 EF Core 5+)
你可以对显式加载的集合添加过滤条件,比如只加载已发布的文章:
await context.Entry(blog)
.Collection(b => b.Posts)
.Query()
.Where(p => p.Title.Contains("EF"))
.LoadAsync();
注意:使用 Query() 可以进一步组合 LINQ 查询,但最终必须调用 LoadAsync() 才会执行数据库查询。
显式加载 vs 其他加载方式
- 贪婪加载(Include):在查询主实体时用 Include 一并加载关联数据。
- 延迟加载(Lazy Loading):访问导航属性时自动加载,需启用代理和虚拟属性。
- 显式加载:手动控制何时加载,更灵活,但需主动调用 Load 方法。
显式加载的优势在于精确控制,避免不必要的数据读取,适合性能敏感或条件复杂的应用场景。
基本上就这些。按需加载用得好,能有效减少数据库压力,提升响应速度。










