What is Entity Framework Code First Migration? A Beginners Guide

Entity Framework Code First development helps us to define the domain model first and then delegate the database creation process to Entity Framework based on the domain model. This is called Domain Driver Design, where the developers will define the domain model as POCO classes and the EF will create the database tables based on the POCO classes.

Read the Quick Start Guide Learn Entity Framework Code First in 10 Minutes to have quick understanding on EF Code First approach. Until, EF 4.3, the only way to manage the database creation from Code First model is using the Database Initializers. As mentioned in the quick start guide, the database initializers are very basic and does not support incremental updations to database schema which is how we will manage database changes in real time. For dealing with this, EF 4.3 released a special tool called Entity Framework Code First Migrations which allows us to manage the database changes that are changing continuously.

Let’s see how to use code first migrations and update the database schema incrementally.

There are primarily 2 ways of performing Code First Migrations,

Code Based Migrations

Automatic Migrations

For migrations, Entity Framework packs a set of commands which are executed from the Package Manager Console. Commands are listed below.

Enable-Migrations

As the name suggests, it helps to enable Code First Migration for our project.

Add-Migration

This commands helps to scaffold incremental migration of changes i.e. to add migrations that scans the model to find the changes after the last database updations.

Update-Database

Performs the actual database updations based on the migration created with add-migration. In simple terms, to upgrade and downgrade database.

This is the configuration class for the migration. The Seed() method helps us to add initial data and it will get called once the database table changes are applied.

Note - It will also add another class file with format [timestamp]_InitialCreate.cs if you have a database created already from Code First model using database initializer. The enable-migrations command will scaffold the existing database and add this initial create migration.

STEP 2 – CREATE Initial Migration

Let’s now add our first migration that creates the initial database structure. Execute the command Add-Migrations [Migration name] for this.

PM> Add-Migration InitialDBCreate

Scaffolding migration 'InitialDBCreate'.

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration InitialDBCreate' again.

PM>

This will add a new migration class file Timestamp_IntialDBCreate.cs as below.

Every migration class will have 2 methods, Up() and Down(). As the name suggests, Up() gets called to upgrade and Down() gets called to downgrade.

STEP 3 – Update or Sync Database

Execute the command Update-Database to deploy the changes to database.

PM> update-database

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.

Applying explicit migrations: [201705020924365_InitialDBCreate].

Applying explicit migration: 201705020924365_InitialDBCreate.

Running Seed method.

PM>

You can see the database got created under App_Data Folder. Open Server Explorer and you can see the database as below,

Adding More Migrations

Now, let’s add another column in Employee model and add a new migration.

[MaxLength(10)]

public string Gender { get; set; }

To add this column into database, add a new migration using add-migration command like below,

PM> add-migration addEmployeeGender

Scaffolding migration 'addEmployeeGender'.

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration addEmployeeGender' again.

PM>

Executing the above command will add a new migration class in Migrations folder. The generated migration class will look like,

Let’s also add another column called IsPermanent to Employee table before creating a new migration.

public bool IsPermanent { get; set; }

Adding migration and Updating Database

PM> add-migration addEmployeeIsPermanent

Scaffolding migration 'addEmployeeIsPermanent'.

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration addEmployeeIsPermanent' again.

PM>

PM> update-database

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.

No pending explicit migrations.

Running Seed method.

PM>

This will add the new column and pump the initial data into Employee and Department table. The final database in server explorer will look like,

You can view the data by clicking “Show Table Data” from server explorer.

The Migrations folder will include all the migrations we added similar to below,

Get All Applied Migrations

To get all the applied migrations,

PM> get-migrations

Retrieving migrations that have been applied to the target database.

201705020942242_addEmployeeIsPermanent

201705020928575_addEmployeeGender

201705020924365_InitialDBCreate

Downgrade Migrations

To downgrade migration to a specific version, we can use update-database command by specifying the version in -targetmigration switch like below,

PM> update-database -TargetMigration:addEmployeeGender

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.

Reverting migrations: [201705020942242_addEmployeeIsPermanent].

Reverting explicit migration: 201705020942242_addEmployeeIsPermanent.

PM>

Using Automatic Migrations

In this migrations, the database changes are automatically applied to database when the model changes. To do this, we need to execute Enable-Migrations command with EnableAutomaticMigrations switch.

PM> Enable-Migrations –EnableAutomaticMigrations

Checking if the context targets an existing database...

Code First Migrations enabled for project GridDemo.

To apply the model changes, execute update-database command as we do for code based migrations. There are few changes which cannot be applied using automatic migrations like column rename etc. In this cases, we need to apply these changes using code based migrations.