Code First Migrations In ASP.NET MVC

Introduction

Before reading code migrations you must know about Entity framework and Architecture of MVC. MVC stands for Model View Controller. I’ve already written about Entity framework code first here Entity framework Code First From Scratch.

What are Code Migrations?

Code migrations are actually database initialization strategies that used in Entity framework code first approach.

Why Use Code Migrations?

After gaining some basic knowledge about code migrations, the second questionthat came to mind is, why do we need code migrations?

Description

In order to understand the concept and working of code migrations you should read my previous article. I’ve already written about installing and using Entity framework with Code First Approach in detail for novice programmers; see Entity Framework Code First from Scratch. We’ll follow the previous article and simply make some changes to our already-built database. Here are the steps we’ll follow.

  • Make a console Application
  • Installing Entity framework package to Solution
  • Make Student Table with Code First
  • Change database connection string to local SQL Server.
  • Perform Read Write Operations on Database.
  • Change the student Table by adding 1 more property to class.
  • What is the error?
  • Resolving the errors. (Updating database…)
  • See the database again.

Example

We’ll work on a simple console application to understand Code Migrations. Let’s create a simple Console Application in Visual Studio.

Console Application

After creating your project, there will be a main function inside a class.

 

  1. namespaceCode_Migrations_in_MVC_EF  
  2. {  
  3.     classProgram  
  4.     {  
  5.         staticvoid Main(string[] args)  
  6.         {}  
  7.     }  
  8. }  
Installing Entity Framework to Solution

It’s time to install entity framework to the project. Open solution explorer. Use shortcut [Ctrl + Alt + L] to open solution explorer. Right click to solution explorer and Click “Manage nuget packages for the solution”. Nuget window will be opened after that.

Manage nuget packages for the solution

Select the Browse tab and search for “EntityFramework”. Select project to install EF and click Install button.

EntityFramework

Now you’ll see the references for the entity framework has been added to your project.

                           entity framework

Developing Database using Code Frist

It’s time to make a database for CRUD operations. Make a Student Classand associate that class with Database Context Class.

Add Student class as given,

Add Student class

Now add a database context class for the database activities. Inherit “StudentDatabase” with “DbContext” class. You might receive some error as I’m receiving the error in the following picture. You’re facing this error because adding entity framework reference to solution is not enough, You must include that library into your C# file in order to work with it.

DbContext

To overcome that error include the following library to your program. You’ll see the errors will be removed after including EF library into file.

library

Now add Student class to your context class in order to couple the entities object with database class objects. Update your Context class with following code.

Context class

There is one more important thing -- we are going to work on code migrations so it would be easy for us to see the changes in Student class that are directly effecting our database table, so we shall change the database connection string towards SQL Server installed into the system. If Microsoft SQL Server is not installed to your system you can skip this. Open App.config file from solution explorer.

App.config

App.config file will be like this. See the space below the configSections. We’ll add our customized connection string to force our database to be created  into our SQL Server. If you don’t know how to create database in SQL Server while working with Code Frist read Change Connection String for SQL Server local in Entity framework Code First in order to change configuration for database connection string.

Hope you’ve understood everything. Now everything is ready. We shall add some data to the table and then read that data from table. To perform this, update your main method with the code.

code

After adding this code build your project and then run it. Program will ask for input, and provide some name and press enter, it will take time to show the success message.

message

Now open up your SQL Server. You can see that the database with the name of “StudentDatabase” has been created and a table with name “Students” has been created also.

StudentDatabase

It’s time to change the database model.

Update student class with following code and just add one more property and run your code again.

property

Program will ask for input and after that the program will show error.

Program

This error is telling  us that your database model has been changed and there is no match between your SQL Server (physical database) and code classes. Here we need Code First Migrations to update the physical database according to model.

Default Behavior of Code First Migrations

Besure default code first migrations are set to off. You need to enable them before working with code first migrations. To start work with code migrations open the package manager console window.

package manager console

Package manager console will be opened as you can see in following picture.

Package manager

We’ll type the following commands one by one to update our physical database.

 

  • Enable Code First Migrations

    So type Enable-Migrations –EnableAutomaticMigrationsto enable migrations.

    EnableAutomaticMigrationsto

    Code first migrations have been enabled for the project. Let’s see what changes has been reflected to our project. Open solution explorer and see the changes, you’ll notice that a folder named “Migrations” has been added to project which contain a “Configuration.cs” file.

    Migrations

    And if you open the Configuration.cs file, you can see the code for migrations, you may enable or disable migrations by setting the AutomaticMigrationsEnabled property to true or false inside the constructor that class.

    AutomaticMigrationsEnabled = true;

Run Update-Database

Now run command to update database “Update-Database” and watch the results.

Update database

After running this command you can check your database. It has been updated.

Table

Now let’s run the program once again.

Run

This this just one command. You can explore further on official site of Microsoft Entity framework here.

 

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all