0

I have a project connected to a database, created using code-first migrations. All of the migration cs files in Migrations folder are deleted, but there is __MigrationHistory table in database.

Now I need to modify a model and apply changes to database. Can I somehow restore migration files from history table, so that "add-migration" command generate the correct update script?

1
  • You should strongly avoid deleting already applied migrations from your solution. If you can restore files using CVS, it's a good step for you. Now you have inconsistent migrations state - __MigrationHistory table knows that there were migrations that created tables, but your project knows nothing about it. Commented Apr 13, 2016 at 8:00

1 Answer 1

1

Once migrations have been applied to all the deployed databases you care about it is no big deal to just re-establish a new baseline. You lose the ability to roll back to a prior migration, but there are ways to do that if needed. I frequently roll up my migrations or start migrations on existing databases that were not using them.

Here is what you can do to get back in sync:

1) Remove the __MigrationHistory table from your database. 2) Remove your migration folder from the project. 3) enable-migrations 4) add-migration InitialSnapshot -IgnoreChanges // tells EF to do a snapshot only 5) update-database 

Now you will have a single migration with your current model state so now you can go make model changes, add a second migration and generate an update script.

You could also do an idempotent script that will show you all your database objects in case you want to check for missing items:

update-database -Script –SourceMigration $InitialDatabase

See here for details about how EF operates under the hood.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.