How to use the expression <Func <Model, bool >> in Linq for EF, where is the condition?

You already had some questions on this topic (for example, Expression.Invoke in the Entity Framework? ), However I could not find the answer for my specific situation, I would like to define such a method:

public IQueryable<Customer> GetCustomers(Expression<Func<Customer, bool>> condition) { return from p in ctx.Customers.AsExpandable() where condition.Compile()(p) select p; } 

The AsExpandable method refers to LinqKit (as recommended in the thread mentioned above). However, when I try to call my method, for example, it:

 var customers = GetCustomers(c => c.ID == 1); 

It throws an InvalidCastException:

Cannot pass an object of type "System.Linq.Expressions.InstanceMethodCallExpressionN" to enter "System.Linq.Expressions.LambdaExpression". What am I doing wrong?

+3
source share
1 answer

If you want to use the expression tree, you need to pass the expression tree to the LINQ method itself:

 return ctx.Customers.AsExpandable().Where(condition) 
+5
source

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


All Articles