Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c# - LinqKit PredicateBuilder returns all or non rows

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...