Resetting Entity Framework migrations

It’s very often that when working on projects that has years of life and we are using Entity Framework, the migrations growth a lot over time and suddenly we encounter problems when we try to add new ones.

Furthermore, opening the migrations folder and see tons of migration files is not very nice, so we may want to clean the state of the migrations, delete those generated in the years and create a new initial single migration.

So the first step that we need to do is delete the __MigrationHistory table from the sql database:

Now we have to delete the Migrations folder from the Visual Studio project:

After that we are in a clean situation, where we no longer have the migration table on the sql database nor the migrations cs files in the visual studio project.

We need to re-enable the entity framework migrations for the project, with the following command:

enable-migrations -force

The force option is mandatory when we want to override the configuration and run the command more times on the same project.

We can now re-create the first migration that will reapply the entire model:

add-migration InitialMigration

We cannot apply the migration because the objects are already present in the database, we would get a message like this:

There is already an object named ‘Blogs’ in the database.

To avoid this problem we can comment the entire migration, so the update-database command will do nothing on the database but the migration table will be created and populated:

public partial class InitialMigration : DbMigration
public override void Up()
// "dbo.Blogs",
// c => new
// {
// Id = c.Int(nullable: false, identity: true),
// Description = c.String(),
// Post_Id = c.Int(),
// })
// .PrimaryKey(t => t.Id)
// .ForeignKey("dbo.Posts", t => t.Post_Id)
// .Index(t => t.Post_Id);


So, by running the command:


We will have a new clean __MigrationHistory table with the new initial migration.

We’ll have to remove the __MigrationHistory table and reapply the commented migration for all the environments of the application, thus all the environments will be aligned to the same version.

After that we’ll uncomment the initial migration in order to have a consistent situation with the migrations.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s