g.pickardou
g.pickardou

Reputation: 35953

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?

Upvotes: 128

Views: 202121

Answers (13)

Zahari Kitanov
Zahari Kitanov

Reputation: 578

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.

Upvotes: 8

Gizmo3399
Gizmo3399

Reputation: 1869

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

Upvotes: 81

Jack Miller
Jack Miller

Reputation: 7667

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.

Upvotes: 1

Samithe Adhikari
Samithe Adhikari

Reputation: 131

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.

Upvotes: 4

Albert Quist
Albert Quist

Reputation: 1

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.

Upvotes: 0

beggarboy
beggarboy

Reputation: 213

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.

Upvotes: -2

Greck
Greck

Reputation: 190

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

Upvotes: 6

Amadeo Gallardo
Amadeo Gallardo

Reputation: 505

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

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

Kaboom.

Upvotes: 34

NSGaga
NSGaga

Reputation: 14312

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

Upvotes: 156

Florian Winter
Florian Winter

Reputation: 5329

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

Upvotes: 1

Shaahin
Shaahin

Reputation: 1225

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

Upvotes: 0

SAm
SAm

Reputation: 2232

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.

Upvotes: 5

Daf De Giraf
Daf De Giraf

Reputation: 781

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

Upvotes: 68

Related Questions