所以我想根据一些简单的设置自动进行过滤。我的代码是这样的:
public ActionResult Index() // here I want to add filtering for Status I only want to show the active ones
{
IQueryable<Ticket> cases = db.Cases().AsQueryable();
cases = cases.EnablePaging().EnableFilterFor(x => x.Status);
return View(cases);
}
EnableFilterFor 看起来像这样:
public static IQueryable<T> EnableFilterFor<T>(this IQueryable<T> queryable, Expression<Func<T, string>> keySelector)
{
string filterValue= "Active";
//Expression<Func<T, bool>> whereexpresion = keySelector.Compile() == "Active"
queryable = queryable.Where(
//here do the magic !! so that the result will be 'x=>x.Status == filterValue');
);
return queryable;
}
我在谷歌上搜索了很多,尝试了很多不同的方法,但都没有成功。我必须以某种方式组合 keySelector 和 filterValue 才能工作(我需要一个 Expression 才能使 Where 方法工作)。任何帮助将不胜感激。
编辑:在测试了两种解决方案之后(谢谢你们!)我发现 Poke 的解决方案最好。戳他的代码是唯一不改变 SQL 生成方式的代码。当我查看 Servy 他生成的 SQL 时,它总是执行一个 EXTRA Sql 选择查询和一个 EXTRA 并在 WHERE 子句中......不知道为什么 :)
请您参考如下方法:
IQueryable.Where需要 Expression<Func<T, bool>> ,所以这将是我们需要构建的东西。由于我们想要从另一个表达式(Expression<Func<T, string>>)中整合一些东西,我们必须“手动”构建表达式。
所以最后,我们要调用LambdaExpression.Lambda<Func<T, bool>>(…)得到我们对 Where 的表达, 但我们需要填写表达式主体:
// first, we reuse the parameter from the `keySelector` expression
ParameterExpression param = keySelector.Parameters[0];
// The body is now just an equality comparison of the `keySelector`
// body, and the constant `filterValue`
Expression body = Expression.Equal(keySelector.Body, Expression.Constant(filterValue));
// now we just need to create a lambda expression for that body with the
// saved parameter and it’s all done:
queryable = queryable.Where(Expression.Lambda<Func<T, bool>>(body, param));
