2 回答

TA貢獻1818條經驗 獲得超8個贊
由于您正在嘗試在布局(不包含模型)中執行數據庫操作,因此依賴注入可以幫助您。
您可以定義一個具有 DB 訪問方法的類,將其注冊到您的服務,并從任何 View/Controller/pageModel 輕松使用它的方法
我將用代碼解釋:
這是我們的依賴:
public class MyDependency?
{
? ? // You can use dependency injection in a chained fashion,?
? ? // DBContext is injected in our dependency
? ? private readonly DBContext _dbContext;
? ? public MyDependency(DBContext dbContext)
? ? {
? ? ? ? _dbContext = dbContext;
? ? }
? ? // Define a method that access DB using dbContext
? ? public bool CheckInDb()
? ? {
? ? ? ? return dbContext.SomeCheck();
? ? }
}
將其注冊到您的服務中Startup(您的依賴項應在注冊 DBContext 后注冊)
public void ConfigureServices(IServiceCollection services)
{
? ? // Some code here
? ? services.AddDbContext<DBContext>(options =>
? ? ? ? options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
? ? services.AddScoped<MyDependency>();
}
然后在你的布局中:
@inject MyDependency MyDependency
@if(MyDependency.CheckInDb())
{
? ? // Do something
}?
else
{
? ? // Do something else
}
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報