Maxymus
Maxymus

Reputation: 1480

Execute method within linq

Is it possible to execute a method with in Linq ie

var lst = (from ls in testEntity.Month where ls .Month1.ToString()  == hello() select ls).ToList();

     private string  hello()

        {
            return "8";
        }

I know that Linq will not execute itself, while executing this i am getting the following error

LINQ to Entities does not recognize the method 'System.String ToString()' and this method cannot be translated into a store expression.

Upvotes: 0

Views: 320

Answers (1)

Botz3000
Botz3000

Reputation: 39610

Generally, you can call methods in LINQ without problems. The problem you are encountering here is specific to LINQ to Entities. L2E needs to translate all your method calls into the appropriate database statements, and for the method you called it doesn't know how to translate it.

You could rewrite your hello() function to return an expression:

public Expression<Func<string>> hello() {
    return () => "8";
}

that way L2E can translate the statements. If that works, depends on your real code, of course.

Upvotes: 3

Related Questions