如何使用表达式来; Func键<产品型号,布尔>>在LINQ到EF where条件? [英] How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?

查看:148
本文介绍了如何使用表达式来; Func键<产品型号,布尔>>在LINQ到EF where条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有已经对这个话题的一些问题(例如 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键&LT;产品型号,布尔&GT;&GT;在LINQ到EF where条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆