Search code examples
linqentity-framework-corelinqkit

LinqKit Core PredicateBuilder not functioning correctly


I have this query:

var query = LinqKit.PredicateBuilder.New<Resume>();
if (selectedWorkFieldID != 0)
{
   query = query.And(js => js.WorkFieldID == selectedWorkFieldID);
   if (!(selectedJobIDs.Contains(0) && selectedJobIDs.Count() == 1))
   {
       foreach (int jobID in selectedJobIDs)
          query = query.Or(js => js.JobID == jobID);
   }
}

var finalQuery = context.Resumes.AsNoTracking().Include(r => r.ResumeSkills)
    .ThenInclude(rs => rs.Skill).Include(r => r.JobSeeker).ThenInclude(r => r.Profile)
    .AsExpandable().Where(query);
count = finalQuery.Count();

resumes = finalQuery.Skip(args.Skip.Value).Take(args.Top.Value).ToList<Resume>();

This query returns All resumes not filtered ones. When I debug, the debugger curser enters the foreach block that filters with or, and there is one jobID in selectedJobIDs but the query returns all resumes. it seems the predicate builder not working at all. How to solve this?


Solution

  • I changed code to this:

    if (selectedWorkFieldID != 0)
            {
                query = query.And(js => js.WorkFieldID == selectedWorkFieldID);
                if (!(selectedJobIDs.Contains(0) && selectedJobIDs.Count() == 1))
                {
                    var query2 = LinqKit.PredicateBuilder.New<Resume>();
                    foreach (int jobID in selectedJobIDs)
                        query2 = query2.Or(js => js.JobID == jobID);
                    query.And(query2);
                }
            }
    

    and it is corrected.