LINQ的+凡+抽象方法= LINQ到实体无法识别方法 [英] Linq + Where + abstract method = LINQ to Entities does not recognize method

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

问题描述

首先:我知道有关于这个话题之前已经有很多的问题。可是我真的找不到任何解决方案,铁道部我的问题。我的问题是,我使用的是抽象的方法来从dbset选择。我的代码看起来是这样的:

First of all: I know that there were already many questions before about this topic. But I really could not find any solutions mor MY problem. My problem is that I am using an abstract method to select from an dbset. My code looks like this:

var dbe = (from i in dbEntities where IsEqualRecord(me, i) select i);



这是我的抽象方法deklaration:

And this is my abstract method deklaration:

protected abstract bool IsEqualRecord(MEntity modelEntities, DEntity databaseEntity);



MEntity DEntity 是通用的类型。我读过,我在这里声明不能转换为SQL语句。但是,我怎么能解决这个问题?还有没有其他的方法呢?

MEntity and DEntity are generic-types. I've read that my where Statement can't be translated to an sql statement. But how can I solve that problem? Is there any other approach?

请不要票关闭这个问题。我看了看几乎每一个类似的问题在计算器,但我无法找到一个解决方案。

Please don't vote to close this question. I've took a look at nearly every similar question on stackoverflow but I could not find a solution.

推荐答案

的LINQ to Entities查询被转换为SQL由DBMS执行,所以你只能使用代码,可以转换为SQL。一个自定义的C#方法不能转换为SQL,所以EF无法翻译的查询。它是抽象的事实是无关紧要的。

Linq to Entities queries are translated to SQL to be executed by the DBMS, so you can only use code that can be translated to SQL. A custom C# method cannot be translated to SQL, so EF fails to translate the query. The fact that it's abstract is irrelevant.

一个可能的解决办法是更换 IsEqualRecord 通过返回的方法表达式来; Func键< DEntity,布尔>> 可转换为SQL;那么你可以做这样的事情:

A possible workaround would be to replace IsEqualRecord by a method that returns an Expression<Func<DEntity, bool>> that can be translated to SQL; you could then do something like that:

var dbe = dbEntities.Where(MakeEqualityPredicate(me));

...


protected abstract Expression<Func<DEntity, bool>> MakeEqualityPredicate(MEntity m);



MakeEqualityPredicate 方法应该返回一个表达式一个 DEntity 进行比较,以给定的 MEntity 。例如,一个派生类可以实现这样的:

The MakeEqualityPredicate method should return an Expression that compares a DEntity to the given MEntity. For instance, a derived class could implement it like this:

protected override Expression<Func<DEntity, bool>> MakeEqualityPredicate(MEntity m)
{
    return d => d.Id == m.Id;
}

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

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