Search code examples
asp.netvisual-studioasp.net-core

DbContext Ensure Created not working in .NET 8


Hi recently I have switched from .NET Core 3 to .NET 8 and there I can't use the

dbContext.Database.EnsureCreated

Visual Studio 2022 with .NET version 8 does not have a startup file anymore.

I have tried to add the code in the program file but I am getting error. I don't know ho to access the EnsureCreated method in program.cs file.


Solution

  • In .NET 8 we don't have a startup class. We only have a Program.cs file where we can add the register the services and there we can also add the Database EnsureCreated method.

    All you need to do is go to the Program.cs class and before app.UseHttpsRedirection(); Add this code

    using(var scope = app.Services.CreateAsyncScope())
    {
       var dbContext = scope.ServiceProvider.GetRequiredService<ApiDbContext>();
       dbContext.Database.EnsureCreated();
    }