120

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
g.pickardou
  • 32,346
  • 36
  • 123
  • 268

13 Answers13

150

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

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • 10
    so there's not a command to get ef migrations to delete the database itself? – cjb110 Jul 08 '14 at 07:07
  • 1
    ...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 dirty – NSGaga-mostly-inactive Jul 08 '14 at 12:26
  • 1
    I also had to remove the database from the SQL server object explorer. – Steven Jeuris Feb 16 '17 at 22:42
  • 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. – Patric Jul 09 '17 at 08:28
  • 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? – lpacheco Oct 03 '17 at 12:52
  • @lpacheco 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://stackoverflow.com/a/15718190/417747 and especially https://stackoverflow.com/a/10255051/417747. 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). – NSGaga-mostly-inactive Oct 03 '17 at 19:04
  • 2
    @lpacheco 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. – Mark Amery Dec 16 '17 at 20:18
  • Step 2 should probably specify to also remove the db context snapshot – bmw15 Aug 30 '18 at 15:20
  • 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 have – Erick Castrillo Nov 16 '18 at 16:28
73

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
Chris F Carroll
  • 11,146
  • 3
  • 53
  • 61
Gizmo3399
  • 1,719
  • 13
  • 7
67

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

Michael Haren
  • 105,752
  • 40
  • 168
  • 205
Daf De Giraf
  • 771
  • 5
  • 3
  • 2
    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 -f – Tascalator Jul 21 '14 at 13:23
  • 1
    @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. – jk7 Jun 22 '15 at 22:00
  • Perfect answer. Quick and easy! Thnx – sapatelbaps Feb 07 '19 at 10:50
  • 1
    According to EF Core Docs, correct parameter name is -Target (for EF Core 1.1) or -Migration (for EF Core 2.0) – Harvey Darvey Mar 04 '20 at 10:56
33

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

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

Kaboom.

Amadeo Gallardo
  • 495
  • 5
  • 13
  • 5
    why would it be required to execute the same step twice? "update-database -force" I mean – SwissCoder Sep 09 '16 at 08:13
  • Just a small notice: "AutomaticMigrationDataLossAllowed = true;" is required within Configration. – Unicco May 09 '17 at 09:54
  • 2
    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](https://stackoverflow.com/a/16082497/1709587) is more robust. -1 for that, and the unexplained repetition of `update-database -force`. – Mark Amery Dec 16 '17 at 20:31
  • 1
    @SwissCoder - you don't need the same step twice (at least, I didn't). I think that was a typo. – Ed Graham Feb 13 '18 at 14:23
  • @SwissCoder 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. – Evram E. Mar 20 '20 at 15:42
  • @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" – SwissCoder Mar 23 '20 at 15:21
  • 1
    @SwissCoder Honestly i have not noticed, no offence intended – Evram E. Mar 23 '20 at 19:02
6

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.

Zahari Kitanov
  • 510
  • 7
  • 15
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.

SAm
  • 2,154
  • 28
  • 28
  • 12
    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... – Amadeo Gallardo Jan 09 '16 at 13:49
  • This only drops the database if the model changes, OP wants to drop it even without a model change. – Quantic Dec 23 '19 at 20:47
5

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

Greck
  • 170
  • 1
  • 7
  • 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. https://web.archive.org/web/20220707003641/https://entityframeworkcore.com/knowledge-base/54898927/how-to-use-database-migration---after-database-ensurecreated---ef-xamarin-forms – Hugo Jan 20 '23 at 14:34
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.

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://stackoverflow.com/a/15832184/2279059
Community
  • 1
  • 1
Florian Winter
  • 4,750
  • 1
  • 44
  • 69
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.

Jack Miller
  • 6,843
  • 3
  • 48
  • 66
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

Shaahin
  • 1,195
  • 3
  • 14
  • 22
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.

  • 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. – prototypik Aug 25 '20 at 16:29
-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.
beggarboy
  • 173
  • 1
  • 12