Run Auto Migration in Asp.Net Core 6 MVC
2022-08-12T12:23:45 - Vicky Chhetri
Read Time:37 Second
Application DB Context :
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
public DbSet<ModelofTheProgram> ModelofThePrograms { get; set; }
}
Migration Created Using the below command:
add-migration MigrationFIleName
Migration File created with the extra snapshot file. you can check in the migration folder for more details.
Once the migration file is created then only auto migration code may run.
try
{
if (_db.Database.GetPendingMigrations().Count() > 0)
{
_db.Database.Migrate();
}
}catch(Exception ex)
{
}
Try the above code when the program starts.
Register and run the program from the program.cs
SeedDataBase(); in the pipeline of program.cs

Final code to start migration:
void SeedDataBase()
{
using ( var scope= app.Services.CreateScope())
{
var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
dbInitializer.Initialize();
}
}
Thank you