How to transfer a table to Entity Framework code?

I am using Entity Framework with automatic transitions.

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

What I want to do is the opposite, completely selecting a table from the database. However, removing the definition from the 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 example, I want to delete the Company table from the database. To do this, I remove the Companies property from the CompanyContext class. However, it does not work.

What is the correct way to delete tables in EF and, if possible, using automatic migration?

+7
c # entity-framework database-migration ef-code-first ef-migrations
source share
3 answers

The add-migrations command creates the Migrations folder. You can see the [DateStamp] _InitialCreate.cs file containing two methods: Up and Down. The Up method of the InitialCreate class creates database tables that match the sets of entities of the data model, and the Down method removes them. Usually, when you enter the command to roll back the database, the Down method is called. You can see statements like DropIndex, DropForeignKey, DropTable in the Down method.

For the question asked by Emre, write the DropTable statement in the Down method of the [DateStamp] _InitialCreate.cs method and the table will be deleted.

Hope this helps.

+2
source share

You must implement your "IDatabaseInitializer" and create your own logic to perform this operation. For example, visit this

Also see โ€œ How do I use Entity Framework in First Shot-Create mode?โ€ If this can help.

In my own experience, I did this by executing the VS 2010 package console manager dispatcher below

 update-database -StartupProjectName "Your Project Namespace" -script -Verbose โ€“force 

Make sure that the project namespace is selected by default.

+1
source share

Add AutomaticMigrationDataLossAllowed = true; into the Configuration class and automatically undo the tables.

+1
source share

All Articles