0

I deleted some tables thinking they would be recreated on running my application but they weren't and it said couldn't find table. So to rerun the migrations I've deleted them from the migration table. Now when I try update-database it says there is already object xxx in the database (different table to what I deleted)

I'm new to EF-Code First so any help gratefully appreciated :)

2 Answers2

1

Its depending on your data, you want to keep them or no.

  1. You can entirely delete your database and recreate it using Update-Database command.
  2. You can modify your ConnectionString and create correct version of your corrupted database to manually add missing tables and relations.
  3. You can create the correct version of database as I said in 2 and move your existing records from corrupted database into the fresh version of your database using Generate Scripts (use this tutorial, and generate script only for data, not Schema).

Things to note:

  • Entity-Framework keeps track of Tables, Relations, Constraints and Indexes so even an small change in them will make problems for you.
  • Entity-Framework keeps an snapshot of your database schema for every single migration.
  • Tweaking database needs you to be accurate and know what will happens if you do something.
RezaNoei
  • 1,266
  • 1
  • 8
  • 24
  • Thank you very much for your comprehensive answer. I needed to keep the data so did options 2 and 3. I had that I didn't have permissions on master so will need to sort a restore. Otherwise this would've been a good option. – JulyAnn Jackson Mar 31 '23 at 01:43
0

When you use Migrations in Entity Framework, Migrations should be the only way you ever modify the database. That is the whole purpose of migrations, to avoid untracked DB changes.

If you don't like any change that you did, You should first rollback the migration, and then Remove the migration file, both using ef command line tool. Please look at this question to know how to do that.

EF Migrations: Rollback last applied migration?

However, It is advisable to do forward only changes and not remove any migrations that have been deployed. This can cause mismatch in database between environments.

As stated in other answer, There is a migration snapshot file named *DbContextModelSnapshot.cs that tracks the current state of what db should look like. Additionally, In database, You will have migration history table named __EFMigrationsHistory. This table gives you details of migrations that have been applied. Migrations are not applied if the table has an entry for your latest migration.

If you want to understand why you were seeing the issue, you can compare your schema with the DBSnapshot.

Code Name Jack
  • 2,856
  • 24
  • 40
  • 1
    Thank you for replying, I think another mistake I made was to delete all the migrations out of the migration history table thinking that it would re run them all. – JulyAnn Jackson Mar 31 '23 at 01:53