C# Code-First migration, up/down?
Asked Answered
K

3

64

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?

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?

Kopaz answered 19/3, 2012 at 11:42 Comment(0)
S
117

The Up method upgrades your database from its current state (represented by your previous migration) to the state expected by your current code migration. The Down method 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 Down method 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 Down method and downgrade your database.

Shinleaf answered 19/3, 2012 at 11:54 Comment(1)
When we use the EnableAutomaticMigrations option, is it an alternative method to up/down?Rockie
G
36

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:

Update-Database -Target:201407242157114_46

Where my last migration is 47 (where new stuff was added). Here's a nice explanation of how to rollback the database and remove a bad migration.

Hope it might help other magician apprentices :)

Giorgi answered 26/7, 2014 at 16:38 Comment(0)
C
2

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

Chip answered 23/4, 2019 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.