【问题标题】:How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?如何在 Linq to EF where 条件中使用 Expression<Func<Model, bool>>?
【发布时间】:2011-10-17 15:27:32
【问题描述】:

已经有一些关于这个主题的问题(例如Expression.Invoke in Entity Framework?),但是,我找不到针对我的具体情况的答案。 我想定义一个这样的方法:

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”类型。 我做错了什么?

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities linqkit


    【解决方案1】:

    如果要使用表达式树,则需要将表达式树本身传递给 LINQ 方法:

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

    【讨论】:

    • AsExpandable 这里不需要,因为你没有使用Invoke
    • @DCShannon:错字;固定。
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多