升级到 ef core 3.0 后。我在对结果进行分组时遇到问题。
如果我删除分组部分它工作正常。但当然我需要得到总和所以需要它。
IQueryable<ShackGapiModel> models = _context.Offers
.Where(i => i.Amount > 0)
.Select(o => new ShackGapiModel
{
Id = o.Shack.Id,
Title = o.Shack.Title,
AmountOnExchange = o.Amount
})
.GroupBy(i => i.Id)
.Select(s => new ShackGapiModel
{
Id = s.First().Id,
Title = s.First().Title,
AmountOnExchange = s.Sum(a => a.AmountOnExchange)
});
最佳答案
原因是 EFCore 无法将您的 linq 查询转换为 sql 查询。因此,它将数据放入内存并在此之后应用您的 linq。这是非常消耗内存的事情。
https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#linq-queries-are-no-longer-evaluated-on-the-client
Mitigations
If a query can't be fully translated, then either rewrite the query in a form that can be translated, or use AsEnumerable(), ToList(), or similar to explicitly bring data back to the client where it can then be further processed using LINQ-to-Objects.
作为替代方式,I prefer to use Max() , 取组键以外的值时。
IQueryable<ShackGapiModel> models = _context.Offers
.Where(i => i.Amount > 0)
.GroupBy(i => i.Id)
.Select(s => new ShackGapiModel
{
Id = = s.Key.Value,
Title = s.Max(a => a.title),
AmountOnExchange = s.Sum(a => a.AmountOnExchange)
});
关于entity-framework-core - LINQ 表达式 'First()' 无法翻译,将在本地进行评估。使用 groupby 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476969/