entity-framework-core - LINQ 表达式 'First()' 无法翻译,将在本地进行评估。使用 groupby 时

标签 entity-framework-core

升级到 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/

相关文章:

asp.net-core - 有没有办法从已发布的 DLL 运行 EF Core RC2 工具?

c# - Asp.net 核心标识 "The INSERT statement conflicted with the FOREIGN KEY constraint "

c# - 是否可以将小型查询合并为单个查询?

c# - 如何跟踪 Entity Framework Core 事件以进行集成测试?

c# - EF核心: conditional query inside Include method

c# - Entity Framework Core 3,无需连接即可获取外键

postgresql - ef core 5 多对多过滤器

sql-server - Sql Server MacOS/Linux 上用户 sa 的 dotnet ef 脚手架登录失败

asp.net-core - 发布 ASP.NET Core 应用程序时自动执行迁移

c# - 没有 asp.net 应用程序的 Entity Framework 核心种子