Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PredicateBuilder "And" Method not working

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.

like image 823
mikemurf22 Avatar asked Mar 14 '11 21:03

mikemurf22


1 Answers

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.

like image 193
Doctor Jones Avatar answered Sep 29 '22 21:09

Doctor Jones