c# - 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
解决方案
您的数据库不知道您的内存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) ;
推荐阅读
- c# - 如果字符串为空,如何避免 Tostring 异常?
- azure-devops - Azure Devops Build - 警告:不接受包 Android SDK Build-Tools 28.0.3 的许可
- javascript - 添加到主屏幕/在每个页面的屏幕上添加书签
- javascript - 显示对话框后如何创建垫子进度条
- ruby-on-rails - 在 Ruby on Rails 上使用 Chartkick 分组堆积条形图/柱形图
- javascript - Can you include a javascript script and also pass it a non-global variable?
- javascript - 批量发送 API 调用
- javascript - 更改 HTML 文件目录后的 JavaScript 错误
- android - 我无法同时应用“Theme.AppCompat.NoTitleBar”和“colorPrimaryDark”状态栏颜色属性
- python - 仅当某个条件为真时,如何使后台任务运行?