Search code examples
c#asp.net-mvcpredicate

PredicateBuilder.New vs PredicateBuilder.True


I am using PredicateBuilder to create a search/filter section in my action. Here it is:

    [HttpPost]
    public ActionResult Test(int? cty, string inumber, int? page)
    {

        var lstValues =
            db.TableName.Include(x => x.Table1)
                .Include(x => x.Table2)
                .Include(x => x.Table3)
                .ToList();

        var predicate = PredicateBuilder.True<TableName>();

        if (!string.IsNullOrWhiteSpace(inumber))
        {
            predicate = predicate.And(x => x.Inumber == inumber);
        }

        if (!string.IsNullOrWhiteSpace(cty.ToString()))
        {
            predicate = predicate.And(x => x.CtyID == cty);
        }

        if (predicate.Parameters.Count > 0)
        {
            lstValues = db.TableName.AsExpandable().Where(predicate).ToList();
            Session["Paging"] = lstValues;
            ViewBag.Paging = lstValues.ToPagedList(page ?? 1, 2);
            return View(lstValues.ToPagedList(page ?? 1, 2));
        }
        else
        {
            return View(lstValues.ToPagedList(page ?? 1, 2));
        }
    }

Under this line PredicateBuilder.True<TableName>(); I get a green squiggly saying

PredicateBuilder.True() is obsolete. Use PredicateBuilder.New instead.

But I have tried PredicateBuilder.New<T> and my predicate always gets a value of 1 even if I don't have any values coming in for the parameters, so cty, and inumber are null. This returns me an empty table.. when it should be returning all records by entering the else statement with return View(lstValues.ToPagedList(page ?? 1, 2));.

When I use PredicateBuilder.True<T> I get all records returned when all of the parameters are null.

Any idea on why that is? Any help is appreciated.


Solution

  • var predicate = PredicateBuilder.New<TableName>(); is equivalent to Expression<Func<TableName, bool>> predicate = item => false;

    What you want instead is PredicateBuilder.New<TableName>(true); to change the default behaviour to include, rather than exclude.