I have a simple Web API where I have a list of requests. In the model this requests have a value call "RequestDate"
public class Requests
{
[Key]
public int IdRequest { get; set; }
public string RequestType { get; set; } = string.Empty;
public string PickUpAddress { get; set; } = string.Empty;
public string DeliveryAddress { get; set; } = string.Empty;
public string StatusQuote { get; set; } = string.Empty;
public DateTime RequestDate { get; set; } = new DateTime();
}
This is my controller to get the requests data, I have a little implementation to do pagination:
[HttpGet("{page}")]
public async Task<ActionResult<List<Requests>>> Get(int page)
{
var pageResults = 2f;
var pageCount = Math.Ceiling(_context.Request.Count() / pageResults);
var requests = await _context.
.OrderBy(x => x.RequestDate)
.Skip((page - 1) * (int)pageResults)
.Take((int)pageResults)
.ToListAsync();
var response = new RequestResponse
{
Requests = requests,
CurrentPage = page,
Pages = (int)pageCount
};
return Ok(response);
}
So when I call this API, the endpoint for requests goes something like this:
https://localhost:7171/api/Request/1
If I want page two then it's like:
https://localhost:7171/api/Request/2
and so on.
But what I want is to have the possibility to add a filter for the date, this is what my expected result would look like:
https://localhost:7171/api/Request?Initialdate=2022/09/06&FinalDate=2022/09/10
I saw the following page Filtering in ASP.NET Core Web API where he does just what I want, but he doesn't appear to use Entity Framework, besides he put a lot more implementation into the project, so I wonder if EF offers an easier way to accomplish this.
CodePudding user response:
You can use query string parameters to pass the Initialdate and FinalDate along with putting a where condition in your ef query to filter out the dates like
_context.Requests.Where((o => o.RequestDate >= queryParameters.InitialDate &&
o.RequestDate <= queryParameters.FinalDate))