Linq + Where + abstract method = LINQ to Entities does not recognize the method

First of all: I know that before this question there were already many questions. But I really could not find a solution to the problem of MO. My problem is that I am using an abstract method to select from dbset. My code is as follows:

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

And this is my separation of abstract methods:

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

MEntity and DEntity are typical types. I read that my Statement statement cannot be translated into an sql statement. But how can I solve this problem? Is there any other approach?

Please do not vote to close this question. I looked at almost every similar question in stackoverflow, but couldn't find a solution.

+4
source share
1 answer

Linq to Entities queries are converted to SQL, which must be executed by the DBMS, so you can only use code that can be translated into SQL. The C # custom method cannot be translated into SQL, so EF cannot translate the query. The fact that it is abstract does not matter.

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

 var dbe = dbEntities.Where(MakeEqualityPredicate(me)); ... protected abstract Expression<Func<DEntity, bool>> MakeEqualityPredicate(MEntity m); 

The MakeEqualityPredicate method should return an expression that compares DEntity with the given MEntity . For example, a derived class may implement it as follows:

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

Source: https://habr.com/ru/post/1497514/


All Articles