【问题标题】:C# Linq expressions can't loop through data results?C# Linq 表达式不能循环遍历数据结果?
【发布时间】:2020-03-25 08:13:41
【问题描述】:

我正在尝试遍历 IQueryable 结果数据,但在循环中出现错误?

        var pivot =  from f in query
                     group f by new
                     {
                         Account = f.Account
                     }
                    into g
                     select new
                     {
                         Account = g.Key.Account,
                         Com = g.Where(d => d.Party == "Com").Sum(d => d.Amount),
                     };


        foreach (var item in pivot)
        {
            Console.WriteLine($"\t {item.Account} {item.Com}");
        }

我只是想在处理完数据后看看我的数据是什么。

我得到的错误信息是:

System.InvalidOperationException

"处理 LINQ 表达式 'AsQueryable(Where(\r\n 来源: NavigationTreeExpression\r\n 值: 默认(IGroupingf__AnonymousType1, StepTwo>)\r\n
表达式:(未处理的参数:e6),\r\n谓词:(d)=> d.Party == \"Com\"))' by 'NavigationExpandingExpressionVisitor' 失败的。这可能表示 EF Core 中的错误或限制。看 https://go.microsoft.com/fwlink/?linkid=2101433了解更多详情 信息。”

下面是用于创建query的查询

var query = from inn in db.InputTE.Take(getRecord)
                         join y in db.InputYEM on inn.YPerform equals y.YPerform
                         select new StageTwo
                         {
                             Party = inn.Party,
                             Account = y.Account,
                             Amount = inn.Amount
                         };

【问题讨论】:

  • 你得到什么错误?请将其添加到问题中
  • 添加了,在底部
  • @NoobCoder 请发布用于创建“查询”变量的代码
  • @RonanThibaudau 我已将其添加到底部。

标签: c# linq .net-core linq-to-entities


【解决方案1】:

错误消息本质上是说 Linq to Entities 无法将您的表达式充分转换为 SQL。它将不得不将整个数据集加载到内存中进行处理。错误消息中的链接非常详细地介绍了问题 - 值得一读。

此错误是 EF Core 3.0 中的新错误。以前,EF 会悄悄地继续将数据集加载到内存中,这往往会导致开发人员在没有意识到的情况下编写低效查询。

尝试通过将where 子句移动到查询中的group by 之前来简化查询。

这个表达式可能不是你所需要的,但我认为它很接近。

from f in query
where f.Party == "Com"
group by f.Account into g
select new { Account = g.Key, Com = g.Sum(d => d.Amount) }

【讨论】:

  • 感谢您提供的信息,一旦说明就清楚多了。我会做 f.Pary == "Com" 但我需要在某些时候使用更多的派对
猜你喜欢
  • 1970-01-01
  • 2013-09-14
  • 2019-02-18
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2012-08-25
相关资源
最近更新 更多