LinqKit PredicateBuilder returns all or not rows

I'm starting to use the LinqKit PredicateBuilder to create a predicate with OR conditions that are not possible with Linq expressions.

The problem I am facing is if I start with PredicateBuilder.True<MyEntity>() , it returns all the rows , and if I start with PredicateBuilder.False<MyEntity>() , then it returns no rows , except what expressions do I I use it! look at the code below:

  var pre = PredicateBuilder.True<MyEntity>(); pre.And(m => m.IsActive == true); using (var db = new TestEntities()) { var list = db.MyEntity.AsExpandable().Where(pre).ToList(); dataGridView1.DataSource = list; } 

It should return rows with IsActive == true, but it returns all rows!

I tried all possible combinations of PredicateBuilder.True | PredicateBuilder.False with And | Or methods, but they do not work!

+6
source share
1 answer

The And extension method does not change the original predicate — it returns a new predicate representing the original And ed predicate along with the specified predicate.

Effectively, your operations do not change the predicate that your pre variable refers to, that is, you get either all or none of the entries, depending on whether you initialized the original predicate to true or false .

Try:

  var pre = PredicateBuilder.True<MyEntity>(); pre = pre.And(m => m.IsActive); 

If you plan OR predicates together, remember to start with the initial predicate false .

  var pre = PredicateBuilder.False<MyEntity>(); pre = pre.Or(m => m.IsActive); 
+13
source

All Articles