C#LINQ到实体无法识别方法'布尔' [英] C# LINQ to Entities does not recognize the method 'Boolean'

查看:187
本文介绍了C#LINQ到实体无法识别方法'布尔'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在lambda语法如下LINQ表达式:

  VAR myvalue的= 6;从2 = 
变种;
变种为= 8;

VAR解析度= MyList.Where(M = GT; m.person.Id == person.Id
和;&安培; IsBetween(myvalue的,从到))
。选择(X =>新建人{等等等等等等})
.ToList());



IsBetween简单通用的辅助方法,看看我是否有介于两者之间:

 公共BOOL IsBetween< T>(T元素,T开头,T结尾)
{
返回的Comparer< T> .DEFAULT .Compare(元素,开始)GT = 0
和;&安培;比较器< T> .Default.Compare(元素,结束)LT; = 0;
}

现在我得到这个错误,我不知道烫得到解决它:




LINQ到实体无法识别方法'布尔IsBetween [十进制](System.Decimal,System.Decimal,System.Decimal )的方法,而这种方法不能被翻译成店的表情。



解决方案

您不能调用从LINQ到实体查询中的任意方法,如查询的是SQL数据库引擎内执行。你只能调用该框架可以转化为等价的SQL方法。



如果你需要调用任意方法,查询操作者调用方法调用将需要先由 AsEnumerable()运营商,使得调用发生在客户端。要知道,这样一来,所有的结果为 AsEnumerable()将可能被加载到内存中和处理。


$的左侧b $ b

在情况下,您所呼叫的方法足够短,我只想内联的逻辑。在你的情况,你也需要删除的Comparer 通话和 IsBetween(myvalue的,从到)会简直成了 myvalue的> =&从功放;&安培; myvalue的< =为


I have the following linq expression in lambda syntax:

var myValue = 6;
var from = 2;
var to = 8;

var res = MyList.Where(m => m.person.Id == person.Id
                         && IsBetween(myValue, from, to))
                .Select(x => new Person { blah blah blah })
                .ToList());

IsBetween is simple generic helper method to see whether I have something in between:

public bool IsBetween<T>(T element, T start, T end)
{
    return Comparer<T>.Default.Compare(element, start) >= 0
        && Comparer<T>.Default.Compare(element, end) <= 0;
}

Now I get this error, and I don't know hot to get around it:

LINQ to Entities does not recognize the method 'Boolean IsBetween[Decimal](System.Decimal, System.Decimal, System.Decimal)' method, and this method cannot be translated into a store expression.

解决方案

You cannot call arbitrary methods from within a LINQ to Entities query, as the query is executed within the SQL database engine. You can only call methods which the framework can translate into equivalent SQL.

If you need to call an arbitrary method, the query operator calling the method call will need to be preceded by an AsEnumerable() operator such that the call happens client-side. Be aware that by doing this, all results to the left-hand side of AsEnumerable() will potentially be loaded into memory and processed.

In cases where the method you are calling is short enough, I would simply inline the logic. In your case, you would also need to drop the Comparer calls, and IsBetween(myValue, from, to) would simply become myValue >= from && myValue <= to.

这篇关于C#LINQ到实体无法识别方法'布尔'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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