首页 > 解决方案 > LINQ 错误:GroupBy 选择上的 System.NotSupportedException

问题描述

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

例外: Unable to create a constant value of type 'AppDB.Stage.Rules'. Only primitive types or enumeration types are supported in this context.

  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

标签: c#.netlinq

解决方案


您的数据库不知道您的内存rules实际上是什么,并且反过来无法将此语句转换为 SQL

最简单的解决方案是将其保留为 anIQueryable并且不要使用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) ;

推荐阅读