繁体   English   中英

LINQ错误:GroupBy选择上出现System.NotSupportedException

[英]LINQ error: System.NotSupportedException on GroupBy Selection

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. 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

您的数据库不知道您的内存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) ;

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

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) ;

因为rules.ToList()在内存中产生结果,所以不能在通过SQL执行的IQueriable中使用它。 您应该先将数据放入内存,然后再通过其他内存中对象缩小数据范围。

 var valuations = context.stage.ToList()
                .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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM