LINQ错误:GroupBy选择上的System.NotSupportedException

gre*_*nes 1 .net c# linq

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
Run Code Online (Sandbox Code Playgroud)

AAA*_*ddd 5

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

最简单的解决方案是将其保留为IQueriable不使用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) ;
Run Code Online (Sandbox Code Playgroud)

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

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) ;
Run Code Online (Sandbox Code Playgroud)