首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >动态构建EF Where()子句的表达式树

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

Stack Overflow用户
提问于 2020-07-02 20:03:13
回答 1查看 240关注 0票数 1

我希望构建一个可以传递给实体框架查询的Where子句的自定义Where表达式。

下面是我所知道的。

代码语言:javascript
复制
// ???

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,在这种情况下,表达式不应该过滤任何东西(应该是空表达式)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-02 20:09:44

正如您已经假设的那样,您应该使用Expression.AndAlso来实现AND逻辑。如果是这样的话,您可以在true中创建"start“表达式求值,并将其他表达式添加到其中:

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62704213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档