简体   繁体   English

在C#中回滚实体框架迁移

[英]Roll back Entity Framework migrations in C#

Right now I have a service that interacts with a DB using Entity Framework. 现在我有一个使用Entity Framework与数据库交互的服务。 When it starts up it initializes the DB using MigrateDatabaseToLatestVersion<Context, Configuration> and it works well. 启动时,它使用MigrateDatabaseToLatestVersion<Context, Configuration>初始化数据库,它运行良好。

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. 如果出现问题(仅发生一次),我们必须手动运行Update-Database '[previous migration name]' ,然后将所有内容切换回上一个服务器。

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. 也就是说,如果服务启动并且看到其架构落后于1个版本,并且最近的迁移发生在最近的x天内,它将自动回滚架构并接受任何数据丢失。

I'm just not sure how to do it. 我只是不确定该怎么做。

You can accomplish this with the DbMigrator class. 您可以使用DbMigrator类完成此操作 You can look at the __MigrationHistory table before your migration code starts running to see what migration to roll back to. 您可以在迁移代码开始运行之前查看__MigrationHistory表,以查看要回滚的迁移。 Use DbMigrator.Update(string) to specify a specific migration to "update" to (you'll roll back because you specified a previous migration). 使用DbMigrator.Update(字符串)指定要“更新”的特定迁移(由于您指定了先前的迁移,因此将回滚)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM