LINQ to Entities Where clause with custom method

.net c# entity-framework entity-framework-core linq-to-entities

Question

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?

1
0
10/4/2017 9:10:35 AM

Accepted Answer

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 below link -

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/

4
10/4/2017 9:36:47 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow