Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set up automatic migrations in Entity Framework Core 7 for my ASP.NET Core MVC web app project?

I created an ASP.NET Core 7.0 MVC web app project. I added Entity Framework Core (v7.0.5) package from NuGet Package Manager.

How do I enable the automatic migrations for my code first project?

In the EF 4.3 version we would use the

Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppContext,
ProjectName.Migrations.Configuration>("DBConnectionString"));

along with

AutomaticMigrationsEnabled = true;
AutomaticMigrationsDataLossAllowed = true;
ContextKey = "ProjectName.AppContext";

in the configuration class.

like image 473
Qubicon Avatar asked Nov 29 '25 16:11

Qubicon


1 Answers

Here is the solution for automatic migrations (Apply migrations at runtime) in ASP.NET Core 7.0.

After these lines in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddControllersWithViews();

var app = builder.Build();

You need to call context.Database.Migrate().

using (var serviceScope = app.Services.CreateScope())
    {
        var dbContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        dbContext.Database.Migrate();
    }
like image 87
TsvetiZlateva Avatar answered Dec 02 '25 06:12

TsvetiZlateva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!