I have downloaded the predicate builder and am having a difficult time getting it to work with the entity framework. Here is my code: v_OrderDetail is the entity
var context = new OrdersEntities();
Expression<Func<v_OrderDetail,bool>> whereClause = w => true;
var predicate = PredicateBuilder.True<v_OrderDetail>();
predicate.And(w => w.Status == "Work");
var results = context.v_OrderDetail.AsExpandable().Where(predicate);
When I look at the results I get back every order. The And predicate doesn't seem to take. When I look at the predicate.parameters.count it only shows 1. I'm not sure, but I would expect it to show 2 after I add the second one.
Any help is greatly appreciated.
It's because predicate.And
doesn't modify predicate
, it returns a new Expression<Func<v_OrderDetail, bool>>
instead. You need to assign the result somewhere so you can use it.
It will work if you do the following:
predicate = predicate.And(w => w.Status == "Work");
The problem here is that Expression trees are immutable. Each time you modify an expression tree you must do so by creating a brand new one with the required change.
Here's a relevant excerpt from How to modify expression trees from MSDN.
Expression trees are immutable, which means that they cannot be modified directly. To change an expression tree, you must create a copy of an existing expression tree and when you create the copy, make the required changes. You can use the ExpressionVisitor class to traverse an existing expression tree and to copy each node that it visits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With