簡體   English   中英

如何使用 .NET 6 在 aspnet 核心 Web 應用程序中執行 database.ensurecreated()?

[英]How do you do database.ensurecreated() in aspnet core web application using .NET 6?

在 .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();
...

幫助會很棒。

builder.Build()返回的WebApplication具有允許創建范圍的Services屬性:

using(var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
    // use context
}

您還可以使用 CreateScope() 方法的異步版本。 如果你想調用一個等待的方法。

using(var scope = app.Services.CreateAsyncScope())
{
  var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
  //more codes ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM