我想创建一个表示EF Core Linq Query Where
子句中要使用的条件的表达式树对象.
因为这个条件将在不同的查询中使用,所以我想定义它一次,然后在任何地方使用它.
但是,我也希望以方法的形式使用这个条件,这样我就可以在没有Linq的情况下使用它.
所以我的问题是,我是否可以使用构建表达式树对象的方法?我知道当立即将lambda分配给它时,可以从lambda构建表达式树,但我可以从单独定义的方法创建表达式树吗?我的意思是:
using System.Linq.Expressions;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Expression<Func<int, bool>> expressionTree1 = (int x) => x % 2 == 0; // compiles
var lambda1 = (int x) => x % 2 == 0;
// following two don't compile with an error:
// Expression<Func<int, bool>> does not contain a constructor that takes 1 argument
var expressionTree2 = new Expression<Func<int, bool>>(lambda1);
var expressionTree3 = new Expression<Func<int, bool>>(IsEven);
}
private static bool IsEven(int x)
{
return x % 2 == 0;
}
}
所以我想以某种方式从其他地方定义的方法构建Expression<Func<int, bool>>
,如上面的IsEven
.