简体   繁体   中英

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

In a .NET 5 web application, we use code such as the following in startup.cs to initialize the DB using Entity Framework:

using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
    var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    context.Database.EnsureCreated();
}

In .NET 6 though, I get the error that there is no ApplicationServices. I tried the solution proposed here , but then I get a runtime error: 'Cannot resolve scoped service 'WebApplication1.DataAccess.SchoolDbContext' from root provider'. The complete code in my program.cs is as follows:

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

Help would be great.

WebApplication returned by builder.Build() has Services property which allows to create a scope:

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

You can also use the async version of the CreateScope() method. If you want to call an awaitable method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM