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:

protected override void Seed(MvcCricket.Models.CricketerDBContext context)

{

     context.Cricketers.AddOrUpdate(i => i.Name,

         new Cricketer

         {

             Name = "Sachin Tendulkar",

             ODI = 463,

             Test = 198

         },

 

         new Cricketer

         {

             Name = "Saurav Ganguly",

             ODI = 311,

             Test = 113

         },

 

         new Cricketer

         {

             Name = "Rahul Dravid",

             ODI = 344,

             Test = 164

         },

 

         new Cricketer

         {

             Name = "Ricky Ponting",

             ODI = 375,

             Test = 168

         },

 

         new Cricketer

         {

             Name = "Wasim Akram",

             ODI = 356,

             Test = 104

         },

 

         new Cricketer

         {

             Name = "Jacques Kallis",

             ODI = 321,

             Test = 162

         },

 

         new Cricketer

         {

             Name = "Sanath Jayasuriya",

             ODI = 445,

             Test = 110

         }

     );       

}

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:

public string Grade { get; set; }

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

namespace MvcCricket.Models

{

    public class Cricketer

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public int ODI { get; set; }

        public int Test { get; set; }

        public string Grade { get; set; }

    }

}

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.

<table class="table">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.Name)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.ODI)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Test)

        </th>

        <th>

            @Html.DisplayNameFor(model=>model.Grade)

        </th>

        <th></th>

    </tr>

 

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.Name)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.ODI)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Test)

        </td>

        <td>

            @Html.DisplayFor(modelItem=>item.Grade)

        </td>

        <td>

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |

            @Html.ActionLink("Details", "Details", new { id=item.ID }) |

            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

        </td>

    </tr>

}

</table>

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

<div class="control-group">

     @Html.LabelFor(model => model.Test, new { @class = "control-label" })

              <div class="controls">

                     @Html.EditorFor(model => model.Test)

                     @Html.ValidationMessageFor(model => model.Test, null, new { @class = "help-inline" })

              </div>

</div>

 

<div class="control-group">

     @Html.LabelFor(model => model.Grade, new { @class = "control-label" })

              <div class="controls">

                     @Html.EditorFor(model=>model.Grade)

                     @Html.ValidationMessageFor(model => model.Grade, null, new { @class = "help-inline" })

              </div>

</div>

 

<div class="form-actions no-color">

     <input type="submit" value="Create" class="btn" />

</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:

 

new Cricketer

{

    Name = "Sachin Tendulkar",

    ODI = 463,

    Test = 198,

    Grade="A"

},

 

new Cricketer

{

    Name = "Saurav Ganguly",

    ODI = 311,

    Test = 113,

    Grade="A"

},

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:

 

namespace MvcCricket.Migrations

{

    using System;

    using System.Data.Entity.Migrations;

   

    public partial class Grade : DbMigration

    {

        public override void Up()

        {

            AddColumn("dbo.Cricketers", "Grade", c => c.String());

        }

       

        public override void Down()

        {

            DropColumn("dbo.Cricketers", "Grade");

        }

    }

}

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. 

Up Next
    Ebook Download
    View all
    Learn
    View all