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

Time:03-15

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.

CodePudding user response:

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
}
  • Related