Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force drop and re-create a a selected table in code-first migration?

I want to drop a table with a thousand columns and let migration re-create it. I can issue a

    DropTable("MyTableWithManyColumns");

But the problem is I would do a manual create table like this

    CreateTable(
            "dbo.MyTable",
            c => new
                {
                    RowId = c.Int(nullable: false, identity: true),
                    // many columns follow...
                })
            .PrimaryKey(t => t.RowId);

The easier way to do this is use SSMS and right click Drop Create Table to new window and execute from there.

But is there is there an easy way using code migration?

like image 997
Alexander Avatar asked Dec 14 '15 12:12

Alexander


People also ask

How do you drop a table in code first approach?

Delete table from database using entity framework core code first approach is so simple you have to remove or comment that table from context file, add migration and then update the database. Now you can see that your table is removed from your database.


1 Answers

I can see two possible ways:

  1. Drop the table from database
  2. Generate a new migration (using Add-Migration). A new migration that creates the missing table will be generated
  3. Execute Migration (using Update-Database)

OR

  1. Remove the entity from the context (remember to remove all relationships with others entities)
  2. Generate a Migration using Add-Migration (it will generate a drop table method)
  3. Execute Migration using Update-Database
  4. Add the entity to the context
  5. Generate a new Migration using Add-Migration (it will generate a create table method)
  6. Execute Migration using Update-Database

Hope it helps!

like image 128
Fabio Luz Avatar answered Nov 01 '22 17:11

Fabio Luz