5

已经有一些关于这个主题的问题(例如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”类型。我究竟做错了什么?

4

1 回答 1

5

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

return ctx.Customers.AsExpandable().Where(condition)
于 2011-10-17T15:30:36.923 回答