【问题标题】:EF Core 3.0 SumAsync triggers aggregate function exceptionEF Core 3.0 SumAsync 触发聚合函数异常
【发布时间】:2020-03-10 16:32:21
【问题描述】:

我正在升级到 EF Core 3.0 和 .NET Core 3.0,但我的一些查询停止工作。这是一个例子:

我有一个名为Bins 的表,我还有另一个名为BinItems 的表,现在它当然是一对多的关系。 BinItems 有一个名为 Qty 的属性,我想根据客户端在过滤器中给出的标准总结来自 BinItems 的所有 Qty

代码如下:

var query = _binRepository.Table;


if (filter.LastRecountDate != null) {
    query = query.Where(x => x.LastRecountDate.Date == filter.LastRecountDate.Value.Date);
}

if (filter.StartRecountDate != null) {
    query = query.Where(x => x.LastRecountDate.Date >= filter.StartRecountDate.Value.Date);
}

if (filter.EndRecountDate != null) {
    query = query.Where(x => x.LastRecountDate.Date <= filter.EndRecountDate.Value.Date);
}

if (filter.Active != null) {
    query = query.Where(x => x.Active == filter.Active);
}

if (!string.IsNullOrEmpty(filter.BinLocation)) {
    query = query.Where(x => x.BinLocation == filter.BinLocation);
}

if (!string.IsNullOrEmpty(filter.Gtin)) {
    query = query.Where(x => x.BinItems.Any(o => o.UPC == filter.Gtin));
}

if (filter.WarehouseIds.Count() > 0) {
    query = query.Where(x => filter.WarehouseIds.Contains(x.Zone.Id));
}

if (!string.IsNullOrEmpty(filter.Keywords)) {
    query = query.Where(x => x.BinItems.Select(o => o.UPC).Contains(filter.Keywords));
}

query = query.Include(x => x.BinItems).Include(x => x.Zone);

if (!string.IsNullOrEmpty(filter.Keywords)) {
    return await query.SumAsync(x => x.BinItems.Where(p => p.UPC.Contains(filter.Keywords)).Sum(o => o.Qty));
}

return await query.SumAsync(x => x.BinItems.Sum(o => o.Qty));

我抛出异常:

Microsoft.Data.SqlClient.SqlException (0x80131904):无法执行 包含聚合或 子查询。

它在 .NET Core 2.1 和 EF Core 2 中运行得非常好,但现在我在我这样做的所有查询中不断收到这些错误。

知道如何在 .NET Core 3.0/EF Core 2 中完成这项工作吗?

【问题讨论】:

  • 这可能是因为他们摆脱了客户端评估,而您的查询在 2.1 中正在本地评估,现在它完全失败了。尝试针对 2.1 运行时运行它,看看是否可以确认。
  • 另见这个问题+你的解释:stackoverflow.com/questions/58092869/…你的问题的解决方案可能是使用groupby。
  • 所以我决定反其道而行之,从 binItems 表开始,其中包含用于 Bins 的包含,现在总和用于 binItems 并且现在可以使用。

标签: c# asp.net-core entity-framework-core asp.net-core-3.0 ef-core-3.0


【解决方案1】:

问题是嵌套聚合(在本例中为SumSum)。 EF Core 3.0 仍然无法正确翻译此类聚合。很可能它在 3.0 之前的版本中工作,客户端评估已在 3.0 中删除。

解决方案像往常一样避免嵌套聚合并在展平(通过SelectMany)集上执行单个聚合。它适用于除Average 之外的所有标准分组聚合。

这是有问题的查询的解决方案(请注意,Includes 是不必要的,因为查询是在服务器端执行的):

var query = _binRepository.Table;
// ... (query filters)

var innerQuery = query.SelectMany(x => x.BinItems);

if (!string.IsNullOrEmpty(filter.Keywords)) {
    innerQuery = innerQuery.Where(x => x.UPC.Contains(filter.Keywords));
}

return await innerQuery.SumAsync(x => x.Qty);
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 2020-03-29
  • 2023-03-19
  • 2019-12-10
  • 2021-08-09
  • 2021-05-26
相关资源
最近更新 更多