将谓词放在变量中

put where predicate in a variable

我首先使用 Entity Framework 代码,我有这样的代码:

var foos = context.Foos.Where(f => f.Bar == "Hello World").ToList();

使用 SQL 分析器,我发现针对数据库的脚本 运行 包含一个 WHERE 语句,正如预期的那样。

但是当我将 Where 谓词放入变量时:

Func<Foo, bool> predicate = f => f.Bar == "Hello World");
var foos = context.Foos.Where(predicate).ToList();

生成的 SQL 命令不再包含 WHERE 语句。

有什么方法可以做到这一点?

改为Expression<Func<Foo, bool>>

Expression<Func<Foo, bool>> predicate = f => f.Bar == "Hello World";

LinqKit could solve this kind issues. It can be obtained by nuget.

关于使用 LinqKitPredicateBuilder 的示例。

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}

工作原理

var predicate = PredicateBuilder.True <Product> ();

// is just a shortcut for this:
Expression<Func<Product, bool>> predicate = c => true;