C# 代码优先迁移,向上/向下?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9769515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Code-First migration, up/down?
提问by Patrick
Started to use the add-migration command in the package manager console to generate the migrations for my model. My question is, the up and down method. I assume that the purpose of the down method is to remove all dependencies and drop the tables if they are already in the database? Also that the down method will be executed before the up method? The up method is then the reverse, create/update tables/indexes etc?
开始在包管理器控制台中使用 add-migration 命令为我的模型生成迁移。我的问题是,上下方法。我假设 down 方法的目的是删除所有依赖项并删除表(如果它们已经在数据库中)?还有就是 down 方法会在 up 方法之前执行?up 方法则相反,创建/更新表/索引等?
Sometimes when i use this then the down method gets a lot of create tables that then are dropped? Recently it created and dropped a lot of tables and almost the same thing happened in the up method. Why?
有时当我使用它时,down 方法会得到很多然后被删除的创建表?最近它创建并删除了很多表,在 up 方法中几乎发生了同样的事情。为什么?
采纳答案by Ladislav Mrnka
The Upmethod upgrades your database from its current state (represented by your previous migration) to the state expected by your current code migration. The Downmethod does the reverse operation - it removes all the changes from the current migration and reverts database to the state expected by the previous migration. It's like installing / uninstalling the migration. Only one of these methods is executed when you call update-database. To use the Downmethod you must explicitly specify the target migration for your upgrade. If the target migration is the old one, the migration API will automatically use the Downmethod and downgrade your database.
该Up方法将您的数据库从其当前状态(由您之前的迁移表示)升级到您当前代码迁移所期望的状态。该Down方法执行反向操作 - 它从当前迁移中删除所有更改,并将数据库恢复到前一次迁移预期的状态。这就像安装/卸载迁移。当您调用update-database. 要使用该Down方法,您必须明确指定升级的目标迁移。如果目标迁移是旧的,迁移 API 将自动使用该Down方法并降级您的数据库。
回答by HerGiz
Just to add to @Ladislav Mrnka. I needed to use Down() for the first time and took me some time to make it work, so:
只是为了添加到@Ladislav Mrnka。我第一次需要使用 Down() 并花了我一些时间让它工作,所以:
Update-Database -Target:201407242157114_46
Where my last migration is 47 (where new stuff was added). Here's a nice explanationof how to rollback the database and remove a bad migration.
我上次迁移的地方是 47(添加了新东西)。这是关于如何回滚数据库和删除错误迁移的很好的解释。
Hope it might help other magician apprentices :)
希望它可以帮助其他魔术师学徒:)
回答by Abdus Salam Azad
Here, Up method will upgrade your database from its current state to the new state expected by you. The Down method will do the reverse. It will revert your database to the state expected from the previous migration
在这里, Up 方法会将您的数据库从当前状态升级到您期望的新状态。Down 方法将执行相反的操作。它将您的数据库恢复到上次迁移的预期状态

