System.InvalidOperationException: 无法对在 Select 中也使用的集合导航上的 Include 使用拆分查询。请在 Include 之前调用 AsSplitQuery() 或移除 Select。
System.InvalidOperationException: Cannot use split query for a query that uses Include on a collection navigation that is also used in a Select. Either call AsSplitQuery() before the Include or remove the Select.
ID: dotnet/ef-core-query-split-query-exception
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Entity Framework Core 7.0 | active | — | — | — |
| Entity Framework Core 8.0 | active | — | — | — |
根因分析
当 LINQ 查询在导航属性上组合使用 'Include' 和投影同一导航的 'Select' 时,与拆分查询执行模式冲突,Entity Framework Core 会抛出此异常。
English
Entity Framework Core throws this when a LINQ query combines 'Include' on a navigation property with a 'Select' that projects the same navigation, conflicting with split query execution mode.
官方文档
https://learn.microsoft.com/en-us/ef/core/querying/single-split-queries#split-queries解决方案
-
在查询链中第一个 'Include' 之前放置 'AsSplitQuery()':'var result = context.Orders.AsSplitQuery().Include(o => o.Items).Where(o => o.Id == 1).ToList();'
-
用显式投影相关数据的 'Select' 替换 'Include':'var result = context.Orders.Where(o => o.Id == 1).Select(o => new { o.Id, Items = o.Items.Select(i => i.Name) }).ToList();'
无效尝试
常见但无效的做法:
-
80% 失败
Adding 'AsSplitQuery()' after 'Include' does not fix the issue; it must be placed before the Include chain.
-
65% 失败
Removing 'Include' and relying solely on lazy loading may cause N+1 query problems and performance degradation.
-
70% 失败
Switching to 'AsSingleQuery()' globally avoids the error but may cause cartesian explosion and slow queries.