如何删除和重新从头创建一个现有的 EF 代码第一数据库

我在 VS 2012中使用 EF 代码优先和 EF 5。我使用 PM update-database命令,并且有一个简单的种子方法用样本数据填充一些表。

我想删除并重新创建我的 x.mdb。更新历史似乎不同步。如果在上下文中注释掉所有 DBSet,则 update-database运行时没有错误,但是在 DB 中留下了一些表。由于我在数据库中没有有价值的数据,似乎最简单的重置所有的东西。

我该怎么做呢?

154918 次浏览

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

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

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.

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

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

Kaboom.

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

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

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

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

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.

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.

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.

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.

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.