我正在創建我的第一個 Blazor Web 應用程式,用于自學目的。有一個帶有資料的簡單資料庫。資料集目前相當小。然而,當點擊頁面鏈接時,加載需要 1-2 秒。只是想知道如果資料集包含大量專案需要多長時間。有沒有辦法先加載頁面然后填充資料?
公共類雇員基礎:組件基礎:
[Inject]
protected IRepository Repository { get; set; }
protected List<BlazorCompanyManager.Data.Employee> employees;
protected override void OnInitialized()
{
this.employees = this.Repository.GetEmployees();
}
公共介面 IRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorCompanyManager.Data
{
public interface IRepository
{
public List<Employee> GetEmployees();
public Employee GetEmployee(Guid id);
public bool UpdateEmployee(Employee employee);
public void AddEmployee(Employee employee);
public void DeleteEmployee(Guid id);
}
}
公共類存盤庫:IRepository:
protected readonly ApplicationDbContext dbContext;
public Repository(ApplicationDbContext db)
{
this.dbContext = db;
}
public List<Employee> GetEmployees()
{
return this.dbContext.EmployeeTable.ToList();
}
我試圖讓它與OnInitializedAsync其他覆寫方法一起作業,但到目前為止沒有成功。任何人都可以就如何做到這一點提出一些想法嗎?
uj5u.com熱心網友回復:
您正在同步運行一個異步代碼塊,從而阻塞了 UI 執行緒。
this.dbContext.EmployeeTable.ToList()
應該是這樣的:
public async ValueTask<List<Employee>> GetEmployeesAsync()
{
using var dbContext = this.DBContext.CreateDbContext();
var list = await dbContext
.EmployeeeTable
.ToListAsync()
?? new List<TRecord>();
return list;
}
為此,您還需要移動到IDbContextFactory存盤庫中的 。您不能再依賴單個 DbContext。
protected virtual IDbContextFactory<MyDbContext> DBContext { get; set; } = null;
public xxxxxRepository(IConfiguration configuration, IDbContextFactory<MyDbContext> dbContext)
=> this.DBContext = dbContext;
啟動/程式
var dbContext = configuration.GetValue<string>("Configuration:DBContext");
services.AddDbContextFactory<MyDbContext>(options => options.UseSqlServer(dbContext), ServiceLifetime.Singleton);
您的組件初始化看起來像這樣。
protected async override void OnInitializedAsyc()
{
this.employees = await this.Repository.GetEmployeesAsync();
}
資料加載將取決于您的資料服務器,但 UI 將回應。隨著資料集的增長,您可能需要考慮分頁 - 您一次只能顯示這么多行,為什么要一次全部獲取它們!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362112.html
上一篇:TensorFlowRecommenders-ValueError:Shapemustberank2butisrank3
