我希望构建一个可以传递给实体框架查询的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,在这种情况下,表达式不应该过滤任何东西(应该是空表达式)。
发布于 2020-07-02 20:09:44
正如您已经假设的那样,您应该使用Expression.AndAlso来实现AND逻辑。如果是这样的话,您可以在true中创建"start“表达式求值,并将其他表达式添加到其中:
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);
}https://stackoverflow.com/questions/62704213
复制相似问题