EF Core 5.0+ 支持通过 Include().Where() 实现关联集合的数据库端筛选,需配合 AsSplitQuery() 避免笛卡尔积;多级筛选可用 ThenInclude().Where();更灵活场景推荐 Select 投影。
EF Core 本身没有内置的 IncludeFilter 方法,但自 EF Core 5.0 起,官方支持在 Include() 中结合 Where、OrderBy 等操作符实现**筛选性加载关联数据**(也称“过滤的包含”)。这个功能常被开发者误称为 IncludeFilter,实际是通过 Include().ThenInclude().Where() 链式表达式完成的。
默认 Include(b => b.Posts) 会加载博客下所有文章。如果只想加载「已发布」的文章,不能直接写 .Include(b => b.Posts.Where(p => p.IsPublished))(语法错误),而要使用 Include 的扩展方式:
List):用 Include(...).Where(...) 形式Microsoft.EntityFrameworkCore 命名空间AsSplitQuery() 或启用全局分割查询,否则可能触发笛卡尔积示例:只加载辽宁省下「状态为启用」的市级数据
var provinces = context.Provinces
.Where(p => p.Name == "辽宁省")
.Include(p => p.Cities)
.ThenInclude(c => c.Districts)
.Include(p => p.Cities)
.Where(c => c.Status == true) // ← 关键:筛选 Cities 集合
.AsSplitQuery() // 推荐加上,避免结果膨胀
.ToList();
若需对更深层级做筛选(比如只加载某市下「2025 年新增」的区县),可在 ThenInclude 后继续加 Where:
IEnumerable 类型),不能用于单个引用属性(如 Author)ON 子句,不是内存过滤LEFT JOIN ... ON ... AND,确保主实体不因子数据不满足条件而丢失示例:查博客,只包含「2025 年发布的文章」及其「点赞数 > 10 的评论」
var blogs = context.Blogs
.Include(b => b.Posts)
.ThenInclude(p => p.Comments)
.Where(c => c.Likes > 10)
.Include(b => b.Posts)
.Where(p => p.PublishDate.Year == 2025)
.AsSplitQuery()
.ToList();
当 Include().Where() 不够灵活(比如要跨表条件、聚合或排序),推荐改用 Select 投影——它在数据库层完成筛选与字段裁剪,性能更好、语义更清晰:
Count、Max 等聚合示例:只取博客名、文章标题和评论数(仅含已发布文章)
var blogSummary = context.Blogs
.Select(b => new
{
BlogName = b.Name,
Posts = b.Posts
.Where(p => p.IsPublished)
.Select(p => new
{
Title = p.Title,
CommentCount = p.Comments.Count()
})
})
.ToList();
这类筛选性加载容易出错,务必注意:
Include 链中对同一集合多次 Where,会编译失败Where 必须紧跟在 Include 或 ThenInclude 后,不能隔开调用AsSplitQuery(),一对多+多对多嵌套可能导致结果集爆炸DateTime.Now.Date 应改用 EF.Functions.DateDiffDay 或参数化)基本上就这些。用对 Include().Where() 和 Select,就能在 EF Core 里干净利落地实现按需加载关联数据。