Joe
Joe

Reputation: 187

What is the best way to implement filtering in ASP.NET Core Web API?

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 ?

Upvotes: 1

Views: 1606

Answers (1)

Jason Roner
Jason Roner

Reputation: 905

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

Upvotes: 2

Related Questions