14

In EF Code first, I want to drop one column from one table & then delete another table.

After removing one column from class file, automatically one migration file generated.

But how to delete table.

what command need to fire? Do I need to delete complete class file & also remove following line from Context file?

 public DbSet<TableClassName> TableClassNameSet { get; set; }

I use, Add Migration 'TableClassName' command.

So what is best way to remove table?

Termininja
  • 6,620
  • 12
  • 48
  • 49
DevPerson
  • 399
  • 1
  • 6
  • 21

3 Answers3

15

If you just made the changes in the last migration, you can rollback that migration. Otherwise, just adjust your models and the changes will be picked up in the next migration. To remove a table, simply remove the corresponding DbSet<MyClass> and any references to that class in other parts of your model and EF will add a DropTable to the migration automatically. If you are no longer using the class for non-Entity Framework purposes you can delete it.

Community
  • 1
  • 1
Steve Greene
  • 12,029
  • 1
  • 33
  • 54
  • Thanks for the answer, for me that's what solved it, I removed any reference in the project of the entity class that I needed to delete, and on generating the DropTable add-migration, the ef generated the DropTable in the UP method. – Misael C. Homem Jul 04 '22 at 16:49
5

To drop a table, you can use DropTable("YourTable") in the Up() method of your DBMigration class.

Also take a look at the following link for more examples on how to customize the migration.

https://msdn.microsoft.com/en-au/data/jj591621.aspx#customizing

Phil G
  • 69
  • 1
  • 9
woodykiddy
  • 6,074
  • 16
  • 59
  • 100
  • 1
    Using DropTable is correct but it's probably better to adjust the model. Also the question seems to be about deleting a table not undoing a migration. Down() is for reversing the latest migration. So from my understanding the code should be in the Up() in this case. – Mikael Eliasson Aug 14 '16 at 06:51
  • @MikaelEliasson Yes, Thanks. Done :) – DevPerson Aug 16 '16 at 14:07
5
  1. Delete from your context class this line

    public DbSet TableClassNameSet { get; set; }

  2. Execute this command:

    Update-DataBase -force -verbose

Efrain Mejias C
  • 196
  • 1
  • 14