Entity Framework: How to delete your old database and start fresh with a new one

In a previous post I explained how to recover after deleting a Entity Framework database. In this post we’ll see the proper way to recreate the database in Entity Framework:

Careful

before you start, make sure you’ve got source-control or back-ups of the code in the Migrations folder. When you delete the Migrations folder, you’re deleting code that:

  1. seeds the database with the initial set of data
  2. and up/downgrades the database to the various versions

In Visual Studio:

  1. Go to Server Explorer, right-click on the data collection that represents your context and choose delete.
  2. Go to Solution Explorer and delete the .mdf file. You might have to click on the “Show All Files” icon before you see it.
  3. Go to the Solution Explorer and delete the Migrations folder.

At this point, you have a solution that will create a new database when its run. If you need to seed the database or expect your models to change, then you’ll want to do the following:

  1. Tell EF to create a fresh database bases on the current models by going to the Package Manager Console and running the following commands:
    Enable-Migrations
    Add-Migration Initial
    Update-Database
    
  2. Update the code in Migrations\Configuration.cs to seed the database with the data you need.