Vladimirs
Vladimirs

Reputation: 8609

How to delete EF migration that adds a new table completely

I am trying to delete migration but that results into some weird scenario.

To create this migrations I:

  1. Created class that represents table in db
  2. Added that to my DbContext
  3. Scaffolded that migration

As a result of that new table created and everything worked as expected. Until I decided that I don't need that table any more (but at that point I already create some of other migrations - so migration that I am trying to delete is not last) so I:

  1. Reverted to one migration before that migration I want to delete
  2. Deleted migration
  3. Deleted that from DbContext
  4. Deleted that class (absolutely smashed that and emptied a recycle bin)
  5. Updated my database

And I got an error: Unable to update database to match the current model because there are pending changes and automatic migration is disabled. In order to find out what exactly is pending I tried to add new migration and that new migration in it's Up method deletes that table that no longer exists and creates that table in Down method (exactly opposite what original migration done).

I even tried to delete my database and generate that from scratch, but no success - getting into the same state.

I tried to experiment with that found odd behaviour:

  1. when I am adding that class back and adding that to DbContext that I get no errors, but no table in database
  2. when I am reverting new migration (that creates a new table in Down) - nothing happens - table isn't created

So how can I completely get rid of that class and migration?

Upvotes: 2

Views: 1621

Answers (1)

Steven U
Steven U

Reputation: 73

You have two options here.

The first is to just add an additional migration to delete the table. This is the easiest and probably the "best practice" route (especially if migration is already in production). Only downside is that you would have 2 migrations that would just be used to cancel each other out. But that isn't necessarily a bad thing. To do this:

  1. Ensure DB is updated to current model (table included)
  2. Delete the entity class
  3. Delete references to it in your DbContext.
  4. Generate a new migration. New migration should just drop the table.
  5. Update database.

If you want to limit the number of migrations for some reason, you would need to do the following:

  1. Delete DB
  2. Delete the migration you want removed and any migrations following it
  3. Remove Entity class
  4. Remove from DbContext
  5. Update DB (you will get a warning saying DB doesn't match models, but this is okay.)
  6. Add Migration
  7. Update DB

Happy Coding.

Upvotes: 2

Related Questions