我的情況是,我的基于 Web 的應用程式在從資料庫(100-200 條記錄)中讀取資料后,在啟用分頁的頁面上顯示之前性能很慢。我按照微軟的例子: https ://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-6.0#add-paging
我發現當我的代碼回圈訪問資料庫中的資料,對其進行處理并將其添加到串列中時,根據我輸出的執行時間,每條記錄大約需要半秒,或多或少。
微軟的例子是:
- 拉取資料
- 處理資料依賴于輸入進行排序、過濾
- 分頁前的資料回傳視圖顯示
當資料庫中有大量記錄時,這聽起來會導致性能問題,因為它首先提取所有內容,然后對其進行分頁。
我想知道提高性能的正確方法是什么?我還應該在重繪 頁面或單擊上一頁/下一頁按鈕時將資料保存在快取/會話中以節省時間嗎?
謝謝你。
更新
下面是Controller中Index Action的關鍵部分:
public IActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
// Read all raw data from DB
var allRequests = (from r in _context.Request).ToList();
// Create the ViewModel object List
List<CreateRequestViewModel> createRequestList = new List<CreateRequestViewModel>();
foreach (Request request in allRequests)
{
CreateRequestViewModel createRequest = new CreateRequestViewModel();
createRequest.RequestId = request.RequestId;
// Some customized code to assign value to the ViewModel object's properties
// Add the ViewModel object to the List
createRequestList.Add(createRequest);
}
// Return the PaginatedList using ViewModel List created above with paging to the page.
return View(PaginatedList<CreateRequestViewModel>.CreateAsync(createRequestList.AsQueryable(), page ?? 1, pageSize));
}
public static PaginatedList<T> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = source.Count();
var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
uj5u.com熱心網友回復:
通常,如果您想在服務器端進行分頁,則必須使用IQueryablecreated fromDbSet<>
public IActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
var query = _context.Request.AsQueryable();
// apply filters to query
...
var result = query.Select(r => new CreateRequestViewModel
{
RequestId = r.RequestId,
// ... other fields
});
// Return the PaginatedList using ViewModel List created above with paging to the page.
return View(PaginatedList<CreateRequestViewModel>.CreateAsync(result, page ?? 1, pageSize));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466549.html
上一篇:大型矩陣線性組合的C 性能優化?
