1

I have a JobsController that has a GetJobs method as follows:

[HttpGet]
... Task<IActionResult> GetJobs([FromQuery] Pagination urlQuery)
... return await _dbContext.Jobs
              .AsNoTracking
              .Where(x => x.BankId == user.BankId)
              .Skip(urlQuery.Limit *(urlQuery.Offset -1))
              .Take(urlQuery.Limit)
              .ToListAsync()

I have successfully implemented paging functionality: .../jobs?limit=25&offset=1

I tried creating a filter class

...
public int BankId {get; set;}
public bool Archived {get; set;}
...
public bool HaveFilter => !string.IsNullOrEmpty(BankId.ToString()) ||
                          !string.IsNullOrEmpty(Archived.ToString())

But then it gets messy when trying to use this alongside Pagination.

What would be the best way to implement server-side filtering so that I can use something like .../jobs?limit=25&offset=1&bankId=3&archived=true ?

1 Answer 1

2

You don't have to chain all the filters in the same statement. Since they all return IQueryable, and not actually performing the database call until ToListAsync is called, you can easily use If statements to chain what you need.

var dataToReturn = _dbContext.Jobs
          .AsNoTracking;

if(BankId > 0)
     dataToReturn = dataToReturn
          .Where(x => x.BankId == user.BankId);

if(Archived)
     dataToReturn = dataToReturn
          .Where(x => x.Archived);  

return dataToReturn
          .Skip(urlQuery.Limit *(urlQuery.Offset -1))
          .Take(urlQuery.Limit);
          .ToListAsync();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer! After getting myself familiar with IQueryable this made sense.
No problem. There are other ways too, like building expression trees but that is a lot more complicated.
Combine this with the Specification pattern if you want to name and avoid duplicating these different components. More here: deviq.com/specification-pattern and in the design pattern library on Pluralsight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.