EF Core 3.1 中的 Group By 和 To Dictionary
Group By and To Dictionary in EF Core 3.1
我们已将一项服务从 .Net Core 2.1 更新到 3.1,在重新评估在转换过程中中断或变慢的查询时,我们遇到了这个查询:
_context.InboundRecords.GroupBy(x => x.State.ToString()).ToDictionary(x => x.Key, x => x.Count())
为了使此 "work" 具有 3.1 重大更改,我们在 DBSet 和分组依据之间添加了一个 to list
_context.InboundRecords.ToList().GroupBy(x => x.State.ToString()).ToDictionary(x => x.Key, x => x.Count())
这里的问题是,这会在进行分组之前将整个 InboundRecords 数据库集带入内存。这与 2.1 的工作方式相同,但必须有更好的方式来做到这一点。我们能否调整此查询以仅返回状态和该状态下的记录数?
Can we tweak this query to only bring back the state and the count of records in that state?
当然可以,方法是 (1) 使用服务器端 GroupBy
和仅包含键/聚合的中间投影,然后 (2) 将客户端转换为所需的形状:
_context.InboundRecords
.GroupBy(x => x.State.ToString())
.Select(g => new { g.Key, Count = g.Count() }) // (1)
.ToDictionary(x => x.Key, x => Count); // (2)
我们已将一项服务从 .Net Core 2.1 更新到 3.1,在重新评估在转换过程中中断或变慢的查询时,我们遇到了这个查询:
_context.InboundRecords.GroupBy(x => x.State.ToString()).ToDictionary(x => x.Key, x => x.Count())
为了使此 "work" 具有 3.1 重大更改,我们在 DBSet 和分组依据之间添加了一个 to list
_context.InboundRecords.ToList().GroupBy(x => x.State.ToString()).ToDictionary(x => x.Key, x => x.Count())
这里的问题是,这会在进行分组之前将整个 InboundRecords 数据库集带入内存。这与 2.1 的工作方式相同,但必须有更好的方式来做到这一点。我们能否调整此查询以仅返回状态和该状态下的记录数?
Can we tweak this query to only bring back the state and the count of records in that state?
当然可以,方法是 (1) 使用服务器端 GroupBy
和仅包含键/聚合的中间投影,然后 (2) 将客户端转换为所需的形状:
_context.InboundRecords
.GroupBy(x => x.State.ToString())
.Select(g => new { g.Key, Count = g.Count() }) // (1)
.ToDictionary(x => x.Key, x => Count); // (2)