Drop or Recreate database with Entity Framework Migrations (Code-First)

16,223

Solution 1

You can get the same behavior with Migrations by using automatic migrations.

PM> enable-migrations -EnableAutomaticMigrations

In Configuration.cs in the constructor, make sure automatic migrations and allow data loss are set to true...

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

Now whenever your model changes, just execute update-database...

PM> update-database

The schema will be changed to match the models and any existing data in the tables will stay there (unless it's in a renamed or removed column). The Seed method is run after the database is updated so you can further control any changes to the data in there.

Solution 2

I went into server explorer and manually deleted all the tables. Then went to the project\Migrations folder and deleted all the migration scripts.

Then a plain old Update-Database -Force did what I needed.

Share:
16,223

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Which is the command to recreate or drop the database when using Entity Framework Migrations, not Initializers?

    What should I write on the package manager console?

    COMMENT:

    I'm looking for some command that gives me the same functionality as Database.SetInitializer<>(new DropCreateDatabaseIfModelChanges<>()); but with the migrations approach.

  • Admin
    Admin over 10 years
    So what if I need to, at this moment, recreate the entire database? Can I do that inside my Seed() method?
  • Anthony Chu
    Anthony Chu over 10 years
    If you need to delete the data and reseed it, you can do that inside the Seed method using standard EF logic. If you're deleting lots of rows, you'll probably want to execute truncate commands on the tables directly by calling context.ExecuteStoreCommand()
  • Admin
    Admin over 10 years
    I'm not getting the point. There isn't a simple way to do it? A single command, a database.Delete() call, etc.?