How to drop a table in Entity Framework Code First

2019-02-21 23:28发布

问题:

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:

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:

You should implement your "IDatabaseInitializer" and create custom logic to do this operation. For example, please visit this

Also please see "How do I use Entity Framework in Code First Drop-Create mode?" if it can help.

In my own experience, I have done it by running the below statement from Package console manager of VS 2010

update-database -StartupProjectName "Your Project Namespace" -script -Verbose –force

Make sure you have "Your Project Namespace" selected as a default project.



回答3:

Add AutomaticMigrationDataLossAllowed = true; to the Configuration class and it will drop tables automatically.