Configuring Code First migrations for early success

These steps assume you have started with an MVC 4 new project, and that you’re just getting started with MVC/EF. Using automatic migrations is really useful for early development/demos, but when you start to get into ‘professional mode’, read this lovely blog post.

Step 1 Enable migrations

In the nuget package manager console type

enable-migrations -EnableAutomaticMigrations

Step 2 Enable automatic application of migrations

In your application start (or other preferred initialization location). Enter the following code (Replace UsersContext with your database context). Database originates from the System.Data.Entity namespace, and Configuration is from your newly added Migrations namespace.

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

Step 3 Enable automatic drop

In Configuration.cs add this code to the constructor.

AutomaticMigrationDataLossAllowed = true;


What does all this do/help with?
The default project does not have migrations automatically enabled. And the error message you receive (if you start querying LINQ objects on your database context) if you don’t will be as follows:
The model backing the 'UsersContext' context has changed since the database was created. Consider using Code First Migrations to update the database (

Enabling migrations sets up the whole migration system. But to enable automatic migrations you have to include -EnableAutomaticMigrations which simply adds the line AutomaticMigrationsEnabled = true; into the newly generated Configurations.cs file.

In conjunction with the database initializer,  development turnaround is more streamlined because you no longer have to type add-migration and update-database every time you make a change. That will happen automatically now. However, that’s not enough, if you want column removals you have to also perform step 3, where automatic data loss is supported.

When you are ready to release software (internally or externally) where you need strict version control and to upgrade databases on site, you should  remove automatic migrations and add a manual migration point.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s