为 EF Where() 子句动态构建表达式树

Dynamically building an expression tree for an EF Where() clause

我想构建一个自定义 Where 表达式,我可以将其传递给 Entity Framework 查询的 Where 子句。

以下是我的全部资料。

// ???

ParameterExpression pe = Expression.Parameter(typeof(StorageDetail), "d");

if (HasRailcarNumber.HasValue)
{
    Expression left = Expression.Property(pe, typeof(StorageDetail).GetProperty("RailcarNumber"));
    Expression right = Expression.Constant(null);
    Expression e2 = (HasRailcarNumber.Value == true) ?
        Expression.Equal(left, right) :
        Expression.NotEqual(left, right);

    // What to do with e2 ???

}

if (IsTakeOrPay.HasValue)
{
    Expression left = Expression.Property(pe, typeof(StorageDetail).GetProperty("TakeOrPayStartDate"));
    Expression right = Expression.Constant(null);
    Expression e2 = (HasRailcarNumber.Value == true) ?
        Expression.Equal(left, right) :
        Expression.NotEqual(left, right);

    // What to do with e2 ???

}

if (HasArrived.HasValue)
{
    Expression left = Expression.Property(pe, typeof(StorageDetail).GetProperty("ArrivalDate"));
    Expression right = Expression.Constant(null);
    Expression e2 = (HasRailcarNumber.Value == true) ?
        Expression.Equal(left, right) :
        Expression.NotEqual(left, right);

    // What to do with e2 ???

}

我的第一个问题是如何启动正文?我不希望我的表达式调用 Where()。我要Where调用我的表情

第二个问题是一旦我有了我的子表达式(上面的e2),我该如何组合它们? (使用 AndAlso。)请注意,这三个属性可能都是 null,在这种情况下,表达式不应过滤任何内容(应该是空表达式)。

正如您假设的那样,您应该将 Expression.AndAlso 用于 AND 逻辑。如果是这种情况,您可以创建评估为 true 的“开始”表达式并向其中添加其他表达式:

Expression expr = Expression.Constant(true);
if (HasRailcarNumber.HasValue)
{
    ...
    expr = Expression.AndAlso(expr, e2);
}
if (IsTakeOrPay.HasValue)
{
    ...
    expr = Expression.AndAlso(expr, e2);
}
if (HasArrived.HasValue)
{
    ...
    expr = Expression.AndAlso(expr, e2);
}