I have a service which uses EF Core runtime migrations on startup:
var migrator = dbContext.Database.GetService<IMigrator>();
await migrator.MigrateAsync("targetMigration", cancellationToken);
To generate the migrations I first update the DbContext class, then perform "dotnet ef migrations add" to generate the migration code.
It may happen that a deployed upgrade will be automatically rolled back to the previous version after a migration has occurred. For example if health checks or tests fail. In this case I want the previous version of the application to be able to automatically roll back the migration. I know MigrateAsync can revert migrations, but in my current workflow the migration code will not be in the previous version of the code, so I am not sure whether it will be able to revert the migration.
I can think of a workflow like:
Change DbContext and run "dotnet ef add migration" to generate the migration code
Revert the DbContext change and deploy the application so that the code for migration 'n' exists, but the target migration in MigrateAsync and the version of the DbContext is 'n-1'
Re-apply the DbContext change, change MigrateAsync to target migration 'n', and deploy the application
But this seems awkward and I am not sure whether it is necessary, and whether it would definitely work.
What is a good strategy for deploying code first runtime migrations using EF Core such that if the previous version is deployed, the migration can be automatically rolled back?