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:
- seeds the database with the initial set of data
- and up/downgrades the database to the various versions
In Visual Studio:
- Go to Server Explorer, right-click on the data collection that represents your context and choose delete.
- Go to Solution Explorer and delete the .mdf file. You might have to click on the “Show All Files” icon before you see it.
- 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:
- 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
- Update the code in
Migrations\Configuration.cs
to seed the database with the data you need.