如何使用Expression>在Linq to EF where条件中
本文关键字:to Linq EF where 条件 boolean Expression 何使用 Func Model | 更新日期: 2023-09-27 18:11:41
已经有一些关于这个话题的问题(例如表达式)。调用实体框架?),但是,我找不到我的具体情况的答案。我想这样定义一个方法:
public IQueryable<Customer> GetCustomers(Expression<Func<Customer, bool>> condition)
{
return from p in ctx.Customers.AsExpandable()
where condition.Compile()(p)
select p;
}
AsExpandable方法来自LinqKit(正如前面提到的线程中建议的那样)。但是,当我尝试像这样调用我的方法时:
var customers = GetCustomers(c => c.ID == 1);
抛出InvalidCastException:
无法强制转换'System.Linq.Expressions '类型的对象。InstanceMethodCallExpressionN'类型'System.Linq.Expressions.LambdaExpression'。我做错了什么?
如果要使用表达式树,则需要将表达式树本身传递给LINQ方法:
return ctx.Customers.AsExpandable().Where(condition)