How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?

别来无恙 提交于 2019-12-10 20:46:23

问题


There have already been some questions about this topic (for instance Expression.Invoke in Entity Framework?), however, I could not find an answer for my specific situation. I would like to define a method like this:

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 is from LinqKit (as it was adviced in the thread mentioned before). However, when I try to call my method like his:

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

It throws an InvalidCastException:

Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.LambdaExpression'. What am I doing wrong?


回答1:


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

return ctx.Customers.AsExpandable().Where(condition)


来源:https://stackoverflow.com/questions/7795986/how-to-use-an-expressionfuncmodel-bool-in-a-linq-to-ef-where-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!