1
votes

I'm using Entity Framework Core (2.0) and I have the following doubt.

I'm not sure about what happens when I do this:

context.Customers.Where(c => MyCustomMethod(c));

bool MyCustomMethod(Customer c) 
{
    return c.Name.StartsWith("Something");
}

Does it translate to SQL without problems?

Is it different than writing:

context.Customers.Where(c => c.StartsWith("Something"));

In short, will I be able to wrap my validations for the Where clase inside a method? Does it break the translation to SQL?

2
Have you tried it? What was the result?Flater
This won't work because EF doesn't know what to do with your MyCustomMethodDavidG
I dnt think you can call like this inside of where and do process, Ef in blind in this caseShiwanka Chathuranga

2 Answers

5
votes

No, you cannot call your custom method in EF LINQ query because EF will not be able to generate expression tree of the method and so it cannot translate it to SQL.

For more info about expression trees, refer to the link.

3
votes

if you need to get string from method you can write same query like this

from customer in contetx.Customer 
                let str = GetString()
                where Name.Any(c=> c.StartsWith(str) )
                select customer;

string GetString() 
{
    return "Something";
}

i dnt know this is helpfull, but this can achieve