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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With