c# - GroupBy 选择的 LINQ 错误 : System. NotSupportedException

标签 c# .net linq

var items = q3.ToList(); 从下面的代码片段执行时,它会抛出异常 System.NotSupportedException。目的是获取分组后的items列表。

异常: 无法创建“AppDB.Stage.Rules”类型的常量值。在此上下文中仅支持原始类型或枚举类型。

  var valuations = context.stage
                .Where(q => q.stageID == stageID && !rules.ToList().Any(r => r.type1 == q.type1 || r.type2 == q.type2))
               .GroupBy(q => q.stageKey)
               .Select(g => g) ;

            var q3 = valuations.Select(y => new StageType
            {
                TypeKey = y.Key,
                TypeName= "UNKNOWN",
            });
            var items = q3.ToList(); //error here

最佳答案

您的数据库不知道内存中的规则实际上是什么,因此无法将此语句转换为 SQL

最简单的解决方案是将其保留为 IQueryable 并且不使用 ToList

context.stage
       .Where(q => q.stageID == stageID && !rules.Any(r => r.type1 == q.type1 || r.type2 == q.type2))
       .GroupBy(q => q.stageKey)
       .Select(g => g) ;

但是,如果它已经在内存中,那么您必须将值作为原始列表发送

var type1s = rules.Select(x => x.type1);
var type2s = rules.Select(x => x.type2);

context.stage
       .Where(q => q.stageID == stageID && !type1s.Contains(q.type1) && !type2s.Contains(q.type2))
       .GroupBy(q => q.stageKey)
       .Select(g => g) ;

关于c# - GroupBy 选择的 LINQ 错误 : System. NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52619981/

相关文章:

c# - 与流程一起打印输出

c# - list clear 是否删除之前包含的对象

满足 WECO 规则所需的 Linq 查询

c# - 使用 iTextSharp 将图像插入 PDF

c# - 让语音识别从句子中挑选一个单词

c# - 以对数方式记录 1、10、100、1000 等

c# - 如何使用证书保护 3 跳 WCF 门面服务?

c# - 反序列化包含字典的对象列表

c# - Linq - 如何映射(选择)解构的元组?

c# - 使用 Linq to Entities 读取 byte[] 或 float