Drop table using SQL and to run migrations on EF Core

59 Views Asked by At

I created a table Documents using Entity Framework Core and the Add-Migration command. I also did some modifications related to foreign key in Table 1 using EF Core migrations and updated the database.

But after some time, I dropped the table Documents using a SQL drop table command instead of deleting it.

Now, how can I sync up my database with my migration state in code? Is there a command to run set of migration from migration mig1 to mig2 and update database?

2

There are 2 best solutions below

3
Sybren S On BEST ANSWER

The problem you have is that your snapshot is out of sync with your actual database.

To fix it:

  1. In your migration snapshot comment out the code that relates to the specific table you deleted.

  2. Do a new migration (add-migration) to 'introduce' your previously deleted table to EF

  3. update-database to apply your migration

0
Gabriel Ribeiro Rossi On
  1. If it's not too complex, manually recreate the table and then create a new migration to remove it.

  2. You can copy the deleted createTable code from the migration file. Create an empty migration, paste it into the most recently generated migration file, and then generate the script or execute the update-database command. This would recreate the deleted database table. After that, you can create a new migration removing the line public DbSet<TableClassName> TableClassNameSet { get; set; } so that EF Core can track the migration correctly.

  3. If the code that creates this table is in a single migration, you can delete the row for this table from the dbo.__EFMigrationsHistory table and then run the update-database command again. a