Entity-Framework Code First Migration

What problems it will solve. Here I will explain how this approach is going to solve these problems. For more details about "Entity-Framework Code First Migration" please check the following link.

Understanding Database Initializer In Entity Framework Code-First Approach 

Here I will work with an example to demonstrate how actually this "Entity-Framework Code First Migration" works.

In short "Entity-Framework Code First Migration" helps in preserving the data even if your model changes. It will maintain the previous record with new record that is why we need this concept. You will get more understanding after checking the above link and reading this article.

Firstly, open Visual Studio 2013. I have my VS 2013, so I am explaining with the same. Create a new project and follow the below steps.

new project

Click OK.

mvc

Choose MVC Template and click OK. Now the project will be loaded, after that check the default Register Model.

registermodel

Now run the Project.
register
Now add a user Account and click Register.
register
Now when you will Register, since the default database Initializer is "CreateDatabaseIfNotExists", it will create a database and the record will save in that.

Now check the database and table.

CreateDatabaseIfNotExists

Now after this I want to add some more fields such as "Email" and "Address" In the model, so for this here are the steps:

cdf user

Now add 2 fields in ApplicationUser.

Now for enabling Migration we should follow the below given 3 steps:

  1. Enable-Migrations
  2. Add-Migration <name>
  3. Update-Database

So we have to follow the 3 steps to enable migration and for making some changes in the database table with these 2 new properties.

Enable-Migration: Open package manager console and type enable Migrations

console

Now the second step is to add-Migration with some name. I will use Details name here.

add-Migration

Now the third step and last one is Update-database.

Update-database

After that go to your table structure and check the table. There you will find these 2 fields.

table

Now if you want to add record and check, just go to your register model and add these 2 fields there.

register view

Add these 2 fields in View as follows.

follow

Now add the following details in controller method.

method

Now build the solution and run it.

register
Now add some details and click register.

register
After adding check your table.

table

Here you will find the 2 records without any data loss.Thus in this way we can achieve migration in code first approach.