[英]Dynamically building an expression tree for an EF Where() clause
I want to build a custom Where
expression that I can pass to the Where
clause of an Entity Framework query.我想构建一个自定义
Where
表达式,我可以将其传递给实体框架查询的Where
子句。
Below is as far as I've got.以下是我所掌握的。
// ???
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 ???
}
My first question is how do I start the body?我的第一个问题是如何启动身体? I don't want my expresion to call
Where()
.我不希望我的表达方式调用
Where()
。 I want Where
to call my expression.我想
Where
调用我的表达式。
Second question is once I have my subexpressions ( e2
above), how do I combine them?第二个问题是一旦我有了我的子表达式(上面的
e2
),我该如何组合它们? (Using AndAlso
.) Note that it's possible that all three properties are null
, in which case the expression should not filter anything (should be a null expression). (使用
AndAlso
。)请注意,所有三个属性都可能是null
,在这种情况下,表达式不应过滤任何内容(应该是 null 表达式)。
As you've assumed you should use Expression.AndAlso
for AND
logic.正如您所假设的那样,您应该使用
Expression.AndAlso
进行AND
逻辑。 If it is the case, you can create "start" expression evaluating to true
and add others to it:如果是这种情况,您可以创建评估为
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.