You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EntityFrameworkCore 5.0.9扩展方法中Eager Loading的Include不生效问题

问题原因

EF Core 中所有针对IQueryable的配置方法(包括Include、ThenInclude、AsSplitQuery、Where等)都不会修改原有的IQueryable对象,而是会返回一个全新的、包含了新增配置的IQueryable实例。你原有扩展方法里直接调用query.Include(xxx)之后没有接收返回值,相当于所有关联加载配置都被丢弃了,最终返回的还是没有加关联加载规则的原始查询,自然不会生效。

你用Load()能生效是因为Load()是立即执行方法,直接把关联数据加载到当前上下文的跟踪缓存中,后续查询实体时会自动装配缓存里的关联数据,但这种方式属于显式加载,性能远不如预加载,不推荐使用。

正确的扩展方法写法

直接返回链式调用的结果即可:

public static class IntegrationServiceExtensions
{
    public static IQueryable<T> LearningObjectContainerIncludeNestedProperties<T>(this IQueryable<T> query) 
        where T : LearningObjectContainer
    {
        return query.Include(x => x.Bases)
            .Include(x => x.LearningObjectives).ThenInclude(x => x.Classifications)
            .Include(x => x.Classifications)
            .Include(x => x.ContainerPropertyImplementations);
    }
}

如果需要搭配拆分查询,同样把方法加入链式调用即可:

public static IQueryable<T> LearningObjectContainerIncludeNestedProperties<T>(this IQueryable<T> query) 
    where T : LearningObjectContainer
{
    return query.Include(x => x.Bases)
        .Include(x => x.LearningObjectives).ThenInclude(x => x.Classifications)
        .Include(x => x.Classifications)
        .Include(x => x.ContainerPropertyImplementations)
        .AsSplitQuery();
}

内容的提问来源于stack exchange,提问作者Ogglas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:21:03