Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading