Reputation: 17186
Right now I have a service that interacts with a DB using Entity Framework. When it starts up it initializes the DB using MigrateDatabaseToLatestVersion<Context, Configuration>
and it works well.
The situation is such that we want to get to a point where we have active/staging environments with one exception: both communicate with the same DB (I don't have control over this).
So, right now, when I deploy to staging, I deploy the service as off. When we switch staging with production, I turn off the production service, start the staging service and it migrates the DB forward as necessary. This works well, and we do this in multiple pre-prod environments. If there's a problem (only ever happened once) we have to manually run Update-Database '[previous migration name]'
and then switch everything back to the previous server.
I'd like to automate migrating backwards in the same way that I have for migrating forwards. That is, if the service starts up and sees that its schema is 1 version behind, and the newest migration occurred within the last x days, it will automatically roll-back the schema and accept any data-loss.
I'm just not sure how to do it.
Upvotes: 3
Views: 664
Reputation: 150108
You can accomplish this with the DbMigrator class. You can look at the __MigrationHistory table before your migration code starts running to see what migration to roll back to. Use DbMigrator.Update(string) to specify a specific migration to "update" to (you'll roll back because you specified a previous migration).
Upvotes: 3