我有一個簡單的 Web API,其中有一個請求串列。在模型中,這個請求有一個值呼叫“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();
}
這是我獲取請求資料的控制器,我有一個小實作來進行分頁:
[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);
}
所以當我呼叫這個 API 時,請求的端點是這樣的:
https://localhost:7171/api/Request/1
如果我想要第二頁,那就是:
https://localhost:7171/api/Request/2
等等。
但我想要的是有可能為日期添加過濾器,這就是我預期的結果:
https://localhost:7171/api/Request?Initialdate=2022/09/06&FinalDate=2022/09/10
我在 ASP.NET Core Web API 中看到了以下頁面Filtering in ASP.NET Core Web API在那里他做了我想要的,但他似乎沒有使用物體框架,除了他在專案中投入了更多的實作,所以我想知道 EF 是否提供了一個更簡單的方法來實作這一點。
uj5u.com熱心網友回復:
您可以使用查詢字串引數來傳遞Initialdate和FinalDate以及在您的 ef 查詢中放置where條件以過濾掉日期,例如
_context.Requests.Where((o => o.RequestDate >= queryParameters.InitialDate &&
o.RequestDate <= queryParameters.FinalDate))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506996.html
標籤:实体框架 asp.net 核心 asp.net-core-webapi 过滤
下一篇:檢查物體框架中是否有0行
