[英]How to add filters in ASP.NET Core Web API using Entity Framework
I have a simple Web API where I have a list of requests.我有一个简单的 Web API ,其中有一个请求列表。 In the model this requests have a value call "RequestDate"在 model 这个请求有一个值调用“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:这是我的 controller 来获取请求数据,我有一个小实现来做分页:
[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:所以当我调用这个 API 时,请求的端点是这样的:
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.我在 ASP.NET Core Web API 中看到了以下页面 Filtering in Z9E0DA8438E1E38A1C30F4B76 CE73B8DDZ来实现这一点。
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您可以使用查询字符串参数来传递Initialdate和FinalDate以及在您的 ef 查询中放置where条件以过滤掉日期,例如
_context.Requests.Where((o => o.RequestDate >= queryParameters.InitialDate &&
o.RequestDate <= queryParameters.FinalDate))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.