如何使用表达式< Func< Model,bool>>>在Linq到EF哪里有条件? [英] How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?
问题描述
已经有关于此主题的一些问题(例如,实体框架中的Expression.Invoke? ),但是,我找不到我的具体情况的答案。
我想定义一个这样的方法:
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;
}
AsExpandable方法来自LinqKit(因为它在前面提到的线程中被提示)。
但是,当我尝试调用我的方法,如他的
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);
它会抛出一个InvalidCastException:
It throws an InvalidCastException:
无法转换类型为System.Linq.Expressions.InstanceMethodCallExpressionN的对象键入System.Linq.Expressions.LambdaExpression。
我做错了什么?
Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.LambdaExpression'. What am I doing wrong?
推荐答案
如果要使用表达式树,您需要将表达式树本身传递给LINQ方法:
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)
这篇关于如何使用表达式< Func< Model,bool>>>在Linq到EF哪里有条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!