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
相关产品推荐
相关产品推荐

