Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping a table using entity framework 6

I'm working on a project using entity framework 6 code first and I am trying to work out the correct way to drop a now obsolete table from the database. There doesn't seem to be much information about this on the web, I know I could simply remove the dbset from my dbcontext, remove the migration file for it and the row from the migrations table in the db but I just wanted to see if that was the only way as this seems a lot of messing about?

like image 504
Chris Sainty Avatar asked May 28 '14 19:05

Chris Sainty


People also ask

How do I drop a table in Entity Framework?

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.

How do I delete all records from a table in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

How do I remove data from Entity Framework?

The common way to delete an entity in Entity Framework is to retrieve the entity from the database into the context and then delete it from the context.


1 Answers

If I understood correctly you are using migrations as well, so it would not be a good idea to simply remove a migration file as it would break the databases that has the newest migrations.

Instead create another migration step after you removed the related DbSet from the DbContext and of course all references of the entity, that has a T parameter of the DbSet, from other entities that are still in the database.

And when you create this new migration step, voila a DropTable(...) migration operation will appear in the Up() function that will remove this table.

I think this is the cleanest and easiest solution for your problem :)

like image 189
Márk Gergely Dolinka Avatar answered Sep 28 '22 14:09

Márk Gergely Dolinka