在 .NET 5 Web 應用程式中,我們在 startup.cs 中使用如下代碼來使用 Entity Framework 初始化 DB:
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
但是在 .NET 6 中,我收到沒有 ApplicationServices 的錯誤。我嘗試了此處提出的解決方案,但隨后出現運行時錯誤:'無法從根提供程式決議范圍服務'WebApplication1.DataAccess.SchoolDbContext'。我的program.cs中的完整代碼如下:
using WebApplication1.DataAccess;
using Microsoft.EntityFrameworkCore;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddRazorPages();
// Setup EF connection
// https://stackoverflow.com/a/43098152/1385857
// https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
builder.Services.AddDbContext<SchoolDbContext>(options =>
options.UseSqlServer(builder.Configuration["Data:SchoolLocal:ConnectionString"]));
WebApplication app = builder.Build();
// https://stackoverflow.com/a/71258326/1385857
SchoolDbContext dbcontext = app.Services.GetRequiredService<SchoolDbContext>();
dbcontext.Database.EnsureCreated();
...
幫助會很棒。
uj5u.com熱心網友回復:
WebApplication由允許創建范圍的builder.Build()has屬性回傳 :Services
using(var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
// use context
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444900.html
標籤:C# asp.net 核心 实体框架核心 .net-6.0
上一篇:如何將影像從ASP.netMVC上傳到資料庫中的VARBINARY
下一篇:將DI物件傳遞給新類的建構式
