LinqKit PredicateBuilder returns all or non rows
Asked Answered
I

2

6

I'm beginning to use LinqKit's PredicateBuilder to create predicate's with OR conditions which is not possible with Linq expressions.

The problem I'm facing is if I begin with PredicateBuilder.True<MyEntity>() it returns all rows and if I begin with PredicateBuilder.False<MyEntity>() it returns non rows, apart from what expressions I use! 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 the rows which has IsActive == true, but it returns all rows!

I have tried all the possible combinations of PredicateBuilder.True | PredicateBuilder.False with And | Or methods, non of them works!

Isotropic answered 10/3, 2013 at 17:30 Comment(0)
P
14

The And extension-method does not modify the original predicate - it returns a new predicate representing the original predicate ANDed together with the specified predicate.

Effectively, your operations are not changing the predicate referred to by your pre variable, meaning you end up with either all or none of the records based 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 are planning toOR predicates together, remember to start off with a false initial predicate.

    var pre = PredicateBuilder.False<MyEntity>();
    pre = pre.Or(m => m.IsActive);
Padishah answered 10/3, 2013 at 17:37 Comment(1)
OMG!! That's a silly mistake. I made the same mistake about string.Replace method 3 years ago!!! Thank you very much.Isotropic
I
0

You forgot to assign pre as said by Ani

pre = pre.And(m => m.IsActive);
Inseparable answered 4/12, 2019 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.