Introduction to Code First Migration and Adding New Property in Application in MVC5

Introduction

In this article, I am introducing you to migration of your code for changes in the Model Class. I described the working process of CRUD Operations and how to work with the LocalDB in MVC5 in my earlier article, so now in here you will learn to work with Entity Framework Code First Migration that will help you to convert any type of change in the Model Class and the change will implement the database also.

In that context, here I am describing my work in two main parts as given below:

  • Migration in Entity Framework Code First
  • Adding New Property

Migration in Entity Framework Code First

The Entity Framework Code First approach creates your database automatically, as you did in my previous article, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.

Let's proceed to the procedure.

Step 1: At first, delete your mdf file located in your "App_Data" Folder in Solution Explorer.

appdata.jpg  

Step 2: Debug your application to ensure that there are no errors.

Step 3: Go to "Package Manager Console" in the "Library Package Manager".

pmc.jpg
 

Step 4: In the Package Manager Console window enter the following command:

Enable-Migrations -ContextTypeName MvcCricket.Models.CricketerDBContext

EnableMigration-in-MVC5.jpg

So, what does it do? It creates a "Configurations.cs" file in the new folder (named Migrations folder) in your Solution Explorer. Check it out here:

Migrations.jpg

Step 5: As you know, your database mdf file has been deleted, so open your "Configuration.cs" file to insert some cricketers details.

Replace the code in Seed Method with the following code:

  1. protected override void Seed(MvcCricket.Models.CricketerDBContext context)  
  2. {  
  3.     context.Cricketers.AddOrUpdate(i => i.Name,  
  4.          new Cricketer  
  5.          {  
  6.              Name = "Sachin Tendulkar",  
  7.              ODI = 463,  
  8.              Test = 198  
  9.          },  
  10.          new Cricketer  
  11.          {  
  12.              Name = "Saurav Ganguly",  
  13.              ODI = 311,  
  14.              Test = 113  
  15.          },  
  16.          new Cricketer  
  17.          {  
  18.              Name = "Rahul Dravid",  
  19.              ODI = 344,  
  20.              Test = 164  
  21.          },  
  22.          new Cricketer  
  23.          {  
  24.              Name = "Ricky Ponting",  
  25.              ODI = 375,  
  26.              Test = 168  
  27.          },  
  28.          new Cricketer  
  29.          {  
  30.              Name = "Wasim Akram",  
  31.              ODI = 356,  
  32.              Test = 104  
  33.          },  
  34.          new Cricketer  
  35.          {  
  36.              Name = "Jacques Kallis",  
  37.              ODI = 321,  
  38.              Test = 162  
  39.          },  
  40.          new Cricketer  
  41.          {  
  42.              Name = "Sanath Jayasuriya",  
  43.              ODI = 445,  
  44.              Test = 110  
  45.          }  
  46.      );  
  47. } 

Note: You will receive an error when you create Cricketer, please resolve it by adding the following library:

using MvcCricket.Models;

Step 6: Build your application

Step 7: Now, you need to start the migration, called Initial Migration. For this you need to create a DbMigration class. What does it do? The Migration class you create helps to create a database, this is the reason for deleting your database mdf file.

In that context, go to your Package Manager Console and enter the following command:

add-migration Initial

AddMigration-in-MVC5.jpg

The add-migration Initial command creates a new class file in your Migration folder. The new class named "(DataStamp)_initial.cs code" helps to create a schema for the database. This file's code implements the Cricketers table in your Cricketer database.

Initial.jpg

Step 8: Enter the following command in your Package Manager Console:

update-database

update.jpg

Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.

Step 9: Debug your application. You can see your Cricketers Details (that you inserted into "Configuration.cs") in your index file of Cricketers.

Index.jpg

Adding New Property

We have mainly three properties in our CricketerDBContext. Let's add a new Grade property to our context. For adding the new property, please follow the procedure given below.

Step 1:  Open your "Cricketer.cs" file and add the following property:

  1. public string Grade { getset; }  

Your Cricketer.cs file will now look like the following code:

  1. namespace MvcCricket.Models  
  2. {  
  3.     public class Cricketer  
  4.     {  
  5.         public int ID { getset; }  
  6.         public string Name { getset; }  
  7.         public int ODI { getset; }  
  8.         public int Test { getset; }  
  9.         public string Grade { getset; }  
  10.     }  
  11. } 

Step 2: Build your solution by pressing "Ctrl+Shift+B".

Step 3: You have successfully added a new property but you need to change your "Index.cshtml" and "Create.cshtml" files to view the Grade field in the browser. So, let's first change your "Index.cshtml" file.

SolutionExplorer.jpg

Change your "Index.cshtml" file with the following code. There are some changes.

  1. <table class="table">  
  2.     <tr>  
  3.         <th>  
  4.             @Html.DisplayNameFor(model => model.Name)  
  5.         </th>  
  6.         <th>  
  7.             @Html.DisplayNameFor(model => model.ODI)  
  8.         </th>  
  9.         <th>  
  10.             @Html.DisplayNameFor(model => model.Test)  
  11.         </th>  
  12.         <th>  
  13.             @Html.DisplayNameFor(model=>model.Grade)  
  14.         </th>  
  15.         <th></th>  
  16.     </tr>  
  17. @foreach (var item in Model) {  
  18.     <tr>  
  19.         <td>  
  20.             @Html.DisplayFor(modelItem => item.Name)  
  21.         </td>  
  22.         <td>  
  23.             @Html.DisplayFor(modelItem => item.ODI)  
  24.         </td>  
  25.         <td>  
  26.             @Html.DisplayFor(modelItem => item.Test)  
  27.         </td>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem=>item.Grade)  
  30.         </td>  
  31.         <td>  
  32.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  33.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  34.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  35.         </td>  
  36.     </tr>  
  37. }  
  38. </table>  
Change your "Create.cshtml" file with the following code. There are some changes.
  1. <div class="control-group">  
  2.      @Html.LabelFor(model => model.Test, new { @class = "control-label" })  
  3.               <div class="controls">  
  4.                      @Html.EditorFor(model => model.Test)  
  5.                      @Html.ValidationMessageFor(model => model.Test, nullnew { @class = "help-inline" })  
  6.               </div>  
  7. </div>  
  8. <div class="control-group">  
  9.      @Html.LabelFor(model => model.Grade, new { @class = "control-label" })  
  10.               <div class="controls">  
  11.                      @Html.EditorFor(model=>model.Grade)  
  12.                      @Html.ValidationMessageFor(model => model.Grade, nullnew { @class = "help-inline" })  
  13.               </div>  
  14. </div>  
  15. <div class="form-actions no-color">  
  16.      <input type="submit" value="Create" class="btn" />  
  17. </div>   

Step 4: You have successfully added a new property, now debug your application.

Note: You will receive an error when accessing your Cricketers folder in the browser URL.

Error.jpg

To solve this error, I am using Code First Migration. Update your Seed method in the "Configurtion.cs" file and add a Grade field in each Cricketer object. For example:

  1. new Cricketer  
  2. {  
  3.     Name = "Sachin Tendulkar",  
  4.     ODI = 463,  
  5.     Test = 198,  
  6.     Grade="A"  
  7. },  
  8. new Cricketer  
  9. {  
  10.     Name = "Saurav Ganguly",  
  11.     ODI = 311,  
  12.     Test = 113,  
  13.     Grade="A"  
  14. }, 

Step 5: Build your solution by pressing "Ctrl+Shift+B".

Step 6: Open Package Manager Console and enter the following command:

add-migration Grade

When the command completes, the new DbMigration class will open automatically. In that code you can see that the new column has been added. For example:

  1. namespace MvcCricket.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.     public partial class Grade : DbMigration  
  6.     {  
  7.         public override void Up()  
  8.         {  
  9.             AddColumn("dbo.Cricketers""Grade", c => c.String());  
  10.         }  
  11.         public override void Down()  
  12.         {  
  13.             DropColumn("dbo.Cricketers""Grade");  
  14.         }  
  15.     }  
  16. } 

Step 7: Build your solution by pressing "Ctrl+Shift+B".

Step 8: Enter the following command in your Package Manager Console:

update-database

update2.jpg

Step 9: Debug your application. Move to the Cricketers folder.

NewIndex.jpg

Step 10: Click on the "CreateNew" link to add more Cricketers.

Create.jpg

Click on "Create".

Final.jpg

Summary

So far this article will help you to learn the Entity Framework Code First Migration, the use of various commands in the Package Manager Console and to add a new field (property) without dropping a database to update a schema. So just go for it.

Thanks for reading my article and don't forget the comments. 


Similar Articles