dotnet data_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-11-05首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://learn.microsoft.com/en-us/ef/core/querying/single-split-queries#split-queries

解决方案

  1. 在查询链中第一个 'Include' 之前放置 'AsSplitQuery()':'var result = context.Orders.AsSplitQuery().Include(o => o.Items).Where(o => o.Id == 1).ToList();'
  2. 用显式投影相关数据的 'Select' 替换 'Include':'var result = context.Orders.Where(o => o.Id == 1).Select(o => new { o.Id, Items = o.Items.Select(i => i.Name) }).ToList();'

无效尝试

常见但无效的做法:

  1. 80% 失败

    Adding 'AsSplitQuery()' after 'Include' does not fix the issue; it must be placed before the Include chain.

  2. 65% 失败

    Removing 'Include' and relying solely on lazy loading may cause N+1 query problems and performance degradation.

  3. 70% 失败

    Switching to 'AsSingleQuery()' globally avoids the error but may cause cartesian explosion and slow queries.