How to delete and recreate from scratch an existing EF Code First database
I am using EF Code First with EF 5 in VS 2012. I use PM update-database
command and I have a simple seed method to fill some tables with sample data.
I would like to delete and recreate my x.mdb. The update history seems to be out of sync. If I comment out all my DBSets in my context, update-database
runs with no error but leaves some tables in the DB. As I have no valuable data in the DB it seems to the simplest to reset the all thing.
How can I accomplish this?
Solution 1:
If I'm understanding it right...
If you want to start clean
:
1) Manually delete your DB - wherever it is (I'm assuming you have your connection sorted), or empty it, but easier/safer is to delete it all together - as there is system __MigrationHistory
table - you need that removed too.
2) Remove all migration files
- which are under Migrations
- and named like numbers etc. - remove them all,
3) Rebuild your project containing migrations (and the rest) - and make sure your project is set up (configuration) to build automatically (that sometimes may cause problems - but not likely for you),
4) Run Add-Migration Initial
again - then Update-Database
Solution 2:
If you worked the correct way to create your migrations by using the command Add-Migration "Name_Of_Migration"
then you can do the following to get a clean start (reset, with loss of data, of course):
-
Update-database -TargetMigration:0
Normally your DB is empty now since the down methods were executed.
-
Update-database
This will recreate your DB to your current migration
Solution 3:
For EntityFrameworkCore you can use the following:
Update-Database -Migration 0
This will remove all migrations from the database. Then you can use:
Remove-Migration
To remove your migration. Finally you can recreate your migration and apply it to the database.
Add-Migration Initialize
Update-Database
Tested on EFCore v2.1.0
Similarly for the dotnet ef CLI tool:
dotnet ef database update 0 [ --context dbcontextname ]
dotnet ef migrations add Initialize
dotnet ef database update