c# - DbExpressionBinding 需要一个带有集合 ResultType 的输入表达式

标签 c# entity-framework linq linq-to-entities

我想按列对表进行分组并获取计数,然后使用结果创建字典。最后一条语句返回错误

DbExpressionBinding requires an input expression with a collection ResultType.

错误是什么意思?

var a = context.Table;
var b = a.GroupBy(x => x.RecordType, (k, cnt) => new { RecType = k, cnt = k.Count() });
var c = b.Select(x => 
    new KeyValuePair<string, Tuple<Type, int>>(
        x.RecType, Tuple.Create(ObjTypes[x.RecType], x.cnt)))
    .ToDictionary(x => x.Key, x => x.Value);

最佳答案

你的 GroupBy调用有点错误 - 它忽略了 cnt范围。应该这样写:

var b = a.GroupBy(x => x.RecordType, (k, cnt) => new { RecType = k, cnt = cnt.Count() });

该异常消息是我见过的最无用的消息之一。问题是当你调用 CountRecordType (别名为 k )在 C# 表达式中编译得很好,因为 string工具 IEnumerable<char> .不幸的是,当 EF 尝试将该表达式转换为 SQL 时,它需要能够使用 SQL count运算符,不能在 string 上工作- 它需要对一系列行进行操作。这会导致您收到有点神秘的异常。

顺便说一下,分配给 c 的查询也不会工作 - Tuple.Create不能翻译成 SQL,ObjTypes[x.RecType] 也不能.您需要调用 ToList关于变量 b在您对结果进行所有其他调整之前。

关于c# - DbExpressionBinding 需要一个带有集合 ResultType 的输入表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653037/

相关文章:

c# - MVC 5 未正确验证 StringLength 属性

c# - 这是将 xml 值加载到结构中的最有效方法吗?

c# - StructureMap 在 Web API 帮助页面 ModelDescriptionLink.cshtml 中导致 Stack Empty 异常

c# - 代码优先 EF : While searching database table is it possible to retrieve list of items it has in DataModel?

c# - 具有行号的 Windows 窗体文本框?

c# - 一个数据库上的多个 DbContext 代码优先迁移

C#/LINQ to SQL - 对来自两个不同结果集的组合结果进行排序

c# - ASP.NET Core 5 Blazor WASM、gRPC、Entity Framework Core 5 : many-to-many results in stack overflow

c# 新手 : if statement && with int

C# 进度条不合作