Search code examples
c#-4.0ef-code-firstpredicatebuilderlinqkit

LINQKit predicate for code first


I have read this (http://www.albahari.com/nutshell/predicatebuilder.aspx)

Here is my code :

var predicateOuter = PredicateBuilder.True<T_Users>();
predicateOuter.And(d => d.code== 357);
var count=tService.GetCount(predicateOuter.Expand());

my service in code first:

public int GetCountSearch(Expression<Func<T, bool>> exp)
{
    return _entities.Count(exp);
}

all record in T_Users: 6548

all record where code==357 : 26

But it always returns all records. but why ?


Solution

  • You need to use the results of Add:

    // Assign result here to predicateOuter -
    predicateOuter = predicateOuter.And(d => d.code== 357);
    
    // This should now function properly
    var count = tService.GetCount(predicateOuter.Expand());
    

    Add doesn't modify the predicate, but rather returns a new one with the additional criteria.