【问题标题】:Dynamically building an expression tree for an EF Where() clause为 EF Where() 子句动态构建表达式树
【发布时间】:2020-07-02 20:03:13
【问题描述】:

我想构建一个自定义 Where 表达式,我可以将其传递给实体框架查询的 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,在这种情况下,表达式不应过滤任何内容(应为空表达式)。

【问题讨论】:

    标签: c# .net .net-core reflection expression-trees


    【解决方案1】:

    正如您所假设的,您应该使用 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);
    }
    

    【讨论】:

    • 谢谢。我如何将 Expression 转换为 Where() 条件 (Expression<Func<StorageDetail, bool>>)?
    • 你应该使用Expression.Lambda。类似的东西:Expression.Lambda<Func<StorageDetail, bool>>(expr, pe)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多