How to delete and recreate from scratch an existing EF Code First database
Asked Answered
T

13

125

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?

Tunicle answered 16/4, 2013 at 10:59 Comment(0)
E
153

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

Exhibitor answered 18/4, 2013 at 12:5 Comment(9)
so there's not a command to get ef migrations to delete the database itself?Bedesman
...as far as I know (not sure of the latest versions) - EF/migrations are good at 'creating' when no Db, and then 'updating' as you change the code. But when you need to do some admin maintenance you have to get your hands dirtyExhibitor
I also had to remove the database from the SQL server object explorer.Adolf
I had to restart visual studio before running Update-Database to get it working. On the first try an error occured during the generation of the new structures although add-migration went through without any reported issues.Harrietharriett
What if my migrations are hand coded and already deployed in a production server? If I delete my migrations and regenerate them, won't they be inconsistent with the server?Resistor
@Resistor production is a different beast, this is more for local scenarios, sort that out first and then try to match that in production, but that's almost always manual process (at least I'd recommend so). Here are some of the answers of mine related to that, https://mcmap.net/q/181922/-entity-framework-code-first-how-to-run-update-database-for-production-database and especially https://mcmap.net/q/181923/-mvc3-and-code-first-migrations-quot-model-backing-the-39-blah-39-context-has-changed-since-the-database-was-created-quot. And if you've manually altered the migrations (try not to) then of course this doesn't apply. But see the 2 answers, what almost always worked for me was Update-Database -Script, try to understand how it works (3 parts).Exhibitor
@Resistor If you have a production database containing data you don't want to destroy then, uh, I respectfully suggest that a question entitled "How to delete ... an existing ... database" was not quite the right question for you.Louis
Step 2 should probably specify to also remove the db context snapshotMidst
I had the same exact issue, I needed to update my models, then recreate the Migration and update the db Here is what I did: 1 - Updated the models 2 - Deleted Initial migration 3 - Ran Update-database -TargetMigration:0, this should delete all tables in the database 3 - Ran Add-Migration Initial to recreate the migration file 4 - Ran Update-database to recreate the tables based on the models I haveRegent
C
78

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
Crowl answered 2/6, 2018 at 13:44 Comment(5)
Works like a charm!Phanerozoic
@user77232 Sorry to hear it doesnt work on .net 5 anymore. Did they change the commands you use in the package manager? I haven''t worked with EF for a while so im not sure.Crowl
I stand corrected. It's "-Migration 0" I thought you had to put the name of the migration you wanted to revert to. It works in 5!Sethrida
@Sethrida I'm glad to hear it still works! Thanks for the correction.Crowl
Note: Remove-Migration is for EF Core; for projects using EF 6, you have to manually delete the migration file.Stringfellow
G
68

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):

  1. Update-database -TargetMigration:0

    Normally your DB is empty now since the down methods were executed.

  2. Update-database

    This will recreate your DB to your current migration

Grapevine answered 25/2, 2014 at 10:52 Comment(4)
Update-database -TargetMigration:0 needs the -f (force)flag in order to delete everything or else it will say possible data loss. Command should be : Update-database -TargetMigration:0 -fSalcido
@Tascalator, I just tried this without -f and there was no warning about possible data loss. Using EF 6.1.2, and there was data in the tables that were dropped.Marta
Perfect answer. Quick and easy! ThnxKatelyn
According to EF Core Docs, correct parameter name is -Target (for EF Core 1.1) or -Migration (for EF Core 2.0)Saltatory
B
34

Single Liner to Drop, Create and Seed from Package Manager Console:

update-database -TargetMigration:0 | update-database -force

Kaboom.

Beggs answered 27/9, 2015 at 14:14 Comment(7)
why would it be required to execute the same step twice? "update-database -force" I meanOdontalgia
Just a small notice: "AutomaticMigrationDataLossAllowed = true;" is required within Configration.Diffract
The equivalent syntax in EF Core is just Update-Database 0. Regardless, this isn't a good fit for the OP's case where "The update history seems to be out of sync"; this approach works by running the "Down" migration for every migration so far applied to the database, so if you've deleted a migration that was previously applied then this will fail (and it may similarly fail if you've modified a migration after applying it). The accepted answer is more robust. -1 for that, and the unexplained repetition of update-database -force.Louis
@Odontalgia - you don't need the same step twice (at least, I didn't). I think that was a typo.Corrode
@Odontalgia This is not executing twice, the first "update-database" is actually running all available migrations backwards, meaning that all Down() methods of all migrations are running. Then the second one is running all database migrations as normal, since now the database is at migration 0 which is empty.Retard
@Vima91 as you might have noticed, the answer was edited in 2018. My comment was from 2016 before it read like this: .. update-database -TargetMigration:0 | update-database -force | update-database -force. You can see the history of the edited anwer, when you click on the "edited Feb 16'18"Odontalgia
@Odontalgia Honestly i have not noticed, no offence intendedRetard
P
7

I am using .net Core 6 and this code is directly stripped out of the Program.cs

using Microsoft.EntityFrameworkCore;

namespace RandomProjectName
{
    public class Program
    {
        public static async Task<int> Main(string[] args)
        {
            var connectionString = "Server=YourServerName;Database=YourDatabaseName;Integrated Security=True;";
            
            var optionsBuilder = new DbContextOptionsBuilder<YourDataContext>();
            optionsBuilder.UseSqlServer(connectionString);
            
            var db = new YourDataContext(optionsBuilder.Options);
            db.Database.EnsureDeleted();
            db.Database.Migrate();
        }
    }
}

You should have at minimum initial migration for this to work.

Parvati answered 17/2, 2022 at 15:34 Comment(0)
G
5

How about ..

static void Main(string[] args)
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());  
    // C
    // o
    // d
    // i
    // n
    // g
}

I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.

Gladiatorial answered 9/4, 2015 at 7:15 Comment(2)
This is not a good ida. Chances are that this code may reach Production and you'll end up having quite a headache with your clients...Beggs
This only drops the database if the model changes, OP wants to drop it even without a model change.Polycotyledon
P
5

dbctx.Database.EnsureDeleted(); dbctx.Database.EnsureCreated();

Prado answered 12/6, 2019 at 16:2 Comment(1)
This is a good solution if you want rapid prototyping but shouldn't be used if you intend to apply migrations to the resulting database. This is mainly because the newly created db won't keep track of existing migrations and __EFMigrationsHistory table will be empty, to add migrations to the database we need to manually edit the table and provide the migrations already present. web.archive.org/web/20220707003641/https://…Hay
B
4

There re many ways to drop a database or update existing database, simply you can switched to previous migrations.

dotnet ef database update previousMigraionName    

But some databases have limitations like not allow to modify after create relationships, means you have not allow privileges to drop columns from ef core database providers but most of time in ef core drop database is allowed.so you can drop DB using drop command and then you use previous migration again.

dotnet ef database drop
PMC command 
PM> drop-database

OR you can do manually deleting database and do a migration.

Berserker answered 14/11, 2020 at 17:45 Comment(0)
R
1

If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx

... then this might work:

  1. Delete all .mdf and .ldf files in your project directory
  2. Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode. See also https://mcmap.net/q/159178/-ef5-cannot-attach-the-file-0-39-as-database-39-1-39
Recitative answered 8/2, 2017 at 16:10 Comment(0)
P
1

Using EF6 with ASP.Net Core 5 I found these commands handy during first initialization of the database:

Remove-Migration -force; Add-Migration InitialMigration; Update-Database;

It removes the last migration (should be the only one), creates it again, then refreshes the database. You can thus type these three commands in one line into the Package Management Console after editing your DbContext and it'll update InitialMigration and database.

A little annoying is that it'll compile your project three times in a row but a least no further manual steps (like deleting the migration files) are necessary.


When you remove an entity you'll need to issue Remove-Database before updating. So the line becomes:

Remove-Migration -force; Add-Migration InitialMigration; Remove-Database; Update-Database;

Problematic here: You need to confirm removing the database + 4 rebuilds.

Patroclus answered 19/6, 2021 at 14:8 Comment(0)
N
0

Take these steps:

  1. Delete those object which should be deleted from the context // Dbset<Item> Items{get;set;} and in Nuget Console run these commands
  2. add-migration [contextName]
  3. update-database -verbose

It will drop table(s) that not exist in Context, but already created in database

Nuggar answered 6/1, 2017 at 12:58 Comment(0)
L
0

Let me help in updating the answers here since new users will find it useful. I believe the aim is to delete the database itself and recreate it using EF Code First approach. 1.Open your project in Visual Studio using the ".sln" extention. 2.Select Server Explorer( it is oftentimes on the left) 3.Select SQL Server Object Explorer. 4.The database you want to delete would be listed under any of the localDB. Right-Click it and select delete.

Larrisa answered 25/8, 2020 at 13:51 Comment(1)
It seems like the OP was looking for a command ran on the command line, since they explicitly mentioned update-database, and since he mentions seeding I assume they were looking for an automated solution for testing. Therefore your UI solution is probably not what they're looking for.Liquefy
E
-2

Since this question is gonna be clicked some day by new EF Core users and I find the top answers somewhat unnecessarily destructive, I will show you a way to start "fresh". Beware, this deletes all of your data.

  1. Delete all tables on your MS SQL server. Also delete the __EFMigrations table.
  2. Type dotnet ef database update
  3. EF Core will now recreate the database from zero up until your latest migration.
Envenom answered 28/5, 2020 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.