LINQ表达式 - 在s Select中使用.Any无法翻译。

4

使用Asp.net Core 3.1时,我从一张表中选择并分组LINQ Expression,但是在使用"any"转入"select"时出现了错误。

然而,在asp.net标准中却能正常工作。

代码:

List<GetObj> liste = dbContext.testTable
          .Where(x => x.isActive == true).OrderByDescending(x => x.Id)
          .GroupBy(x => new { x.field1, x.field2 })
          .Select(x => new GetObj
          {
               field1 = x.Key.field1,
               field2 = x.Key.field2,
               totalQuantity = x.Sum(y => y.ldNet),
               isMaped = x.Any(y => y.isLastMove == true)
           }).ToList();

错误结果如下:

.Any(y => y.isLastMove == True)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). 

代码中的 true 和错误信息中的 True 大小写不同,这是有什么原因吗? - Peter Smith
没有任何影响。 - sadullah zolfqar
嘿,你也可以使用C#关键字(如from、where、orderby、group by)来实现更高效的查询。就像这样:from table in dbContext.testTable where table.isActive == true orderby table.Id descedning group new { table.ldNet, table.isLastMove } by new {table.field1, table.field2} into tableGrp select new GetObj { field1 = x.Key.field1, field2 = x.Key.field2, totalQuantity = tableGrp.Sum(x => x.ldNet), isMaped = tableGrp.Max(x => x.isLastMove) }如果你要对不同的列使用orderby,你也可以为它设置一个索引。 - Richárd Baldauf
1个回答

2
目前(EF Core 3.x),仅支持对键/标量聚合进行分组查询的投影,而Any不属于该类别。
这有点不寻常且不易读懂,但由于Any在所有元素条件都为false时返回false,并且true > false,因此Any可以被支持的Max聚合替换:
isMaped = x.Max(y => y.isLastMove)

感谢Ivan Stoev的帮助,这种方式可能不太易读,你有什么建议来解决这个问题吗? - sadullah zolfqar
@sadullahzolfqar 这就是你原来问题的解决方案,你还需要什么其他建议吗? - Ivan Stoev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接