Enabling automatic migrations with Entity Framework 4.3 on an existing database

Now that my online weekly planner WeekPlan has been migrated from Linq2Sql to Entity Framework, I can take advantage of automatic migrations.

This is actually very simple to put in place and will save you (and me) many headaches in the future.

First, execute these two commands in your Package Manager Console:

Enable-Migrations -EnableAutomaticMigrations
Add-Migration InitialMigration -IgnoreChanges

The first one will create a Migrations folder with a Configuration class (that enables the Automatic Migrations).

The second command creates an empty migration so that the future migrations will start from the current state of your database.

Additionally, I needed to add the following line in OnModelCreating method of my DbContext class:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<WeekPlanDataContext, Configuration>());

That’s it! Now, If I add a new column in a model, it will be automatically added to the database schema. Even better than migrations in rails