如何使用表达式来; Func键<产品型号,布尔>>在LINQ到EF where条件? [英] How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?
问题描述
有已经对这个话题的一些问题(例如 Expression.Invoke? ),但是,我无法找到我的具体情况的答案。
我想这样定义一个方法:
公开的IQueryable<客户> GetCustomers的(表达式来; Func键<客户,布尔>>情况):
{由对在ctx.Customers.AsExpandable
()返回
,其中condition.Compile()(P)
。选择所需磷;
}
的
AsExpandable方法是从LinqKit(因为它是在前面提到的线程劝)。
然而,当我尝试调用我的方法就像他的:
VAR的客户= GetCustomers的(C =以及c .ID == 1);
这引发InvalidCastException:
无法转换类型'System.Linq.Expressions.InstanceMethodCallExpressionN对象键入'System.Linq.Expressions.LambdaExpression。
我在做什么错了?
块引用>
解决方案如果你想使用表达式树,你需要表达式树本身传递到LINQ方法:
返回ctx.Customers.AsExpandable(),其中(。条件)
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?
解决方案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键<产品型号,布尔>>在LINQ到EF where条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!