DbExpressionBinding需要具有集合ResultType的输入表达式 [英] DbExpressionBinding requires an input expression with a collection ResultType

查看:111
本文介绍了DbExpressionBinding需要具有集合ResultType的输入表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to group the table by a column and get the counts, then create dictionary using the result. The last statement returns the error of

DbExpressionBinding需要具有集合ResultType的输入表达式.

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参数.应该这样写:

Your GroupBy call is slightly wrong - it's ignoring the cnt parameter. It should be written like this:

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

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

That exception message is one of the more unhelpful I've seen. The problem is that when you call Count on RecordType (aliased as k) in the C# expression it compiles fine, because string implements IEnumerable<char>. Unfortunately, when EF tries to convert that expression to SQL it needs to be able to use the SQL count operator, which can't work on a string - it needs to operate over a sequence of rows. This results in the somewhat cryptic exception you received.

顺便说一句,分配给c的查询也不起作用-Tuple.Create无法转换为SQL,ObjTypes[x.RecType]也不能.您需要先对变量b调用ToList,然后才能对结果进行所有其他调整.

Incidentally, the query assigned to c won't work either - Tuple.Create can't be translated into SQL, nor can ObjTypes[x.RecType]. You'll need to call ToList on variable b before you can do all that additional shaping of your results.

这篇关于DbExpressionBinding需要具有集合ResultType的输入表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆