Perform Code First Migration in ASP.Net MVC 5

Introduction

As you know, we can perform CRUD operations in MVC 5 with an Entity Framework Model and we also work in Paging & Searching in MVC 5. Now, suppose we want to update the database with new details in the Students, Courses and Enrollments entities, then we need to migrate our application.

In that context, you'll learn today to do the Code First Migration in the MVC application. The migration helps you to update and change the data model that you've created for the application and you don't need to re-create or drop your database. So, let's proceed with the following section.

Apply Code First Migration

The data model in the database usually changes after developing the new application. When the data model changes, it becomes out of sync with the database. We've configured our Entity Framework in the app to drop and recreate the data model automatically. When any type of change is done in the entity classes or in the DbContext class, the existing database is deleted and the new database is created that matches the model and sees it with test data.

When the application runs in production, we do not want to loose everything each time we make changes like adding a column. The Code First Migration solved this problem by enabling the code first to update the database instead of dropping or recreating.

Use the following procedure to create a sample of that.

Step 1: Please disable the Database Initializer in the Web.Config file or in the Global.asax file like as in the following:

In Web.Config File: 

  1. <!--<contexts>  
  2.       <context type="Vag_Infotech.DAL.CollegeDbContext, Vag_Infotech">  
  3.         <databaseInitializer type="Vag_Infotech.DAL.CollegeDatabaseInitializer, Vag_Infotech"></databaseInitializer>  
  4.       </context>  
  5. </contexts>-->  

In Global.asax File:

  1. // Database.SetInitializer(new CollegeDatabaseInitializer()); 

 

Step 2: Please change the database name in the Web.Config file like as in the following:

  1. <connectionStrings>   
  2.   <add name="CollegeDbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=VInfotechNew;Integrated Security=SSPI" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  

Step 3: Open the Package Manager Console and enter the following commands:

enable-migration

add-migration InitialCreate 

Package Manager Console in MVC

 

It'll create the Migration folder in your application and Configuration.cs file in it automatically.

Migration Folder in Solution Explorer

You can see the Seed() created in the file and the purpose of this method is to enable the insert or change data after Code First creates or updates the database. 

 

Editing Seed Method

Now, we add new code for updating our data model in this method. When we do not use the migration, the data model is dropped or re-created during the execution of the application each time, but now the data is retained after database changes.

Step 1: Modify your Configuration.cs with the following code: 

  1. namespace Vag_Infotech.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.Data.Entity;  
  6.     using System.Data.Entity.Migrations;  
  7.     using System.Linq;  
  8.     using Vag_Infotech.Models;  
  9.    
  10.     internal sealed class Configuration : DbMigrationsConfiguration<Vag_Infotech.DAL.CollegeDbContext>  
  11.     {  
  12.         public Configuration()  
  13.         {  
  14.             AutomaticMigrationsEnabled = false;  
  15.         }  
  16.    
  17.         protected override void Seed(Vag_Infotech.DAL.CollegeDbContext context)  
  18.         {  
  19.             var New_Students = new List<Student>  
  20.             {  
  21.                 new Student{FirstName="Amit",LastName="Senwal",  
  22.                     EnrollmentDate=DateTime.Parse("2009-07-01")},  
  23.                 new Student{FirstName="Nimit",LastName="Joshi",  
  24.                     EnrollmentDate=DateTime.Parse("2009-07-01")},  
  25.                 new Student{FirstName="Pankaj",LastName="Lohani",  
  26.                     EnrollmentDate=DateTime.Parse("2009-07-05")},  
  27.                 new Student{FirstName="Pravesh",LastName="Khanduri",  
  28.                     EnrollmentDate=DateTime.Parse("2009-10-01")},  
  29.                 new Student{FirstName="Ainul",LastName="Hasan",  
  30.                     EnrollmentDate=DateTime.Parse("2010-07-01")},  
  31.                 new Student{FirstName="Ravi",LastName="Kumar",  
  32.                     EnrollmentDate=DateTime.Parse("2010-07-10")},  
  33.                 new Student{FirstName="Arvind",LastName="Shukla",  
  34.                     EnrollmentDate=DateTime.Parse("2009-09-01")},  
  35.                 new Student{FirstName="Sumit",LastName="Dhasmana",  
  36.                     EnrollmentDate=DateTime.Parse("2009-08-05")},  
  37.             };  
  38.             New_Students.ForEach(ns => context.Students.AddOrUpdate(p => p.LastName, ns));  
  39.             context.SaveChanges();  
  40.    
  41.             var New_Courses = new List<Course>  
  42.             {  
  43.                 new Course{CourseID=201,Name="MCA",Credit=3,},  
  44.                 new Course{CourseID=202,Name="M.Sc.IT",Credit=2,},  
  45.                 new Course{CourseID=203,Name="M.Tech.CS",Credit=2,},  
  46.                 new Course{CourseID=204,Name="M.Tech.IT",Credit=4,}  
  47.             };  
  48.             New_Courses.ForEach(ns => context.Courses.AddOrUpdate(p => p.Name, ns));  
  49.             context.SaveChanges();  
  50.    
  51.             var New_Enrollments = new List<Enrollment>  
  52.             {  
  53.                 new Enrollment{  
  54.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Amit").ID,  
  55.                     CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,  
  56.                     Grade=StudentGrade.A  
  57.                 },  
  58.                 new Enrollment{  
  59.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Nimit").ID,  
  60.                     CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,  
  61.                     Grade=StudentGrade.A  
  62.                 },  
  63.                 new Enrollment{  
  64.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Nimit").ID,  
  65.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,  
  66.                     Grade=StudentGrade.B  
  67.                 },  
  68.                 new Enrollment{  
  69.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Pankaj").ID,  
  70.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Sc.IT").CourseID,  
  71.                     Grade=StudentGrade.A  
  72.                 },  
  73.                 new Enrollment{  
  74.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Pravesh").ID,  
  75.                     CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,  
  76.                     Grade=StudentGrade.A  
  77.                 },  
  78.                 new Enrollment{  
  79.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Pravesh").ID,  
  80.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Sc.IT").CourseID,  
  81.                     Grade=StudentGrade.B  
  82.                 },  
  83.                 new Enrollment{  
  84.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Ainul").ID,  
  85.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,  
  86.                     Grade=StudentGrade.A  
  87.                 },  
  88.                 new Enrollment{  
  89.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Ravi").ID,  
  90.                     CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,  
  91.                     Grade=StudentGrade.B  
  92.                 },  
  93.                 new Enrollment{  
  94.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Arvind").ID,  
  95.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,  
  96.                     Grade=StudentGrade.B  
  97.                 },  
  98.                 new Enrollment{  
  99.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Sumit").ID,  
  100.                     CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,  
  101.                     Grade=StudentGrade.A  
  102.                 },  
  103.                 new Enrollment{  
  104.                     StudentID= New_Students.Single(ns=>ns.FirstName=="Sumit").ID,  
  105.                     CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,  
  106.                     Grade=StudentGrade.D  
  107.                 },  
  108.             };  
  109.    
  110.             foreach (Enrollment et in New_Enrollments)  
  111.             {  
  112.                 var NewEnrollDb = context.Enrollments.Where(  
  113.                     ns => ns.Student.ID == et.StudentID &&  
  114.                         ns.Course.CourseID == et.CourseID).SingleOrDefault();  
  115.                 if (NewEnrollDb == null)  
  116.                 {  
  117.                     context.Enrollments.Add(et);  
  118.                 }  
  119.             }  
  120.             context.SaveChanges();  
  121.         }  
  122.     }  
  123. } 
In the code above the Seed() takes the context object as an input argument and in the code the object is used to add the entities to the database. We can see how the code creates the collection for the database for each entity type and then saves it by SaveChanges() and adds it through the DbSet property. It is not necessary to call the SaveChanges() after each group of entities.

Step 2: Build the solution.

Migration Executing

Step 1: Enter the following command in the Package Manager Console:

update-database

Update Database in Packge Manager

Step 2: Run the application and see the changes in the Students link.

Updated Page in MVC

Summary

This article has introduced you to the code first migration and how to apply it to the application. You can also view the benefits of migrating the database in the application. In the next article we'll see the DataAnnotations in the application. Thanks for reading.


Similar Articles