How to drop a table in Entity Framework Code First?

c# database-migration ef-code-first ef-migrations entity-framework

Question

I am using Entity Framework with Auto Migrations.

So when I add a new model to my Context, my database is updated and new table is created.

What I want to do is the opposite, droping the table completely from database. However, removing the definition from Context class does not work.

public class CompanyContext : DbContext
{
    public DbSet<Permission> Permissions { get; set; }
    public DbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       base.OnModelCreating(modelBuilder);
    }
}

For instance, I want to remove Company table from database. To do that, I remove Companies property from CompanyContext class. However, it is not working.

What is the proper way to drop tables in EF and using auto migrations if possible ?

1
8
10/26/2017 6:08:06 AM

Popular Answer

The add-migrations command creates a Migrations folder. You can see [DateStamp]_InitialCreate.cs file containing two methods viz.; Up and Down. The Up method of the InitialCreate class creates the database tables that corresponds to the data model entity sets, and the Down method delete them. Typically when you enter a command to rollback a database, Down method is called. You can see statements like DropIndex, DropForeignKey, DropTable statements in Down method.

In case of question asked by Emre, write the DropTable statement in the Down method of [DateStamp]_InitialCreate.cs class and the table will be dropped.

Hopefully it will help.

2
4/21/2014 12:20:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow