Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Entity Framework Code First Auto Migration Using ASP.NET MVC 5

0.00/5 (No votes)
3 Nov 2015 1  
In this tip, we will try to understand SOLID Architecture principles using simple ASP.NET MVC 5 examples.

Introduction

I know there are many articles on this subject. But I am writing this tip to understand Entity Framework Code First with simple C# examples. Here, I also describe how to do auto migration. I think it will be very helpful for a beginner.

Any suggestions for improvements are welcome and you can post a comment below.

Creating a Project

First of all, we have to create a project. Open Visual Studio (I use VS 2013). Select File-->New-->Project, then a popup box is shown as below:

From left side, you can see that I select Visual C# Web option. In name section, you have to write your project name. In this project, I will give a name Rakib33_EFCodeFirst. Then Ok button will enable and click it. Next, you will find another popup box as below:

Here, I select MVC, also Web API and Individual User Accounts for Security. Security contains Identity table. I will describe about Microsoft ASP.NET Identity later. Now click OK button and see our project will be created. From Menu, select View-->Solution Explorer, then you see the project property, all folders and files are as given below:

Create a Database

Now we create a database in Microsoft SQL Server. I use MS SQL Server 2012. Go to View-->Server Explorer from project menu, then select Connect to Database icon as shown below:

Click this icon (red block) and a Add Connection popup box will appear as shown below:

In Server Name section, put your Microsoft SQL Server name, then select 'Use SQL Server Authentication' and put Server User Name(sa) and Password. Give a Database name in Select or enter a database name section. Here, I put a name CodeFirstDB. You can change it. Now click ok. Then a confirm box appears if our given database name does not exist in SQL Server.

Simply Click Yes. Now CodeFirstDB will be created. See in Server Explorer:

Creating the Model Class

In this project, I will show master details relationship between two classes, one School as master class and Student as child or details class. And a Db Context class with Microsoft Identity table. All model classes are in Models folder in the project. Let&risque;s see the code at a glance.

//
// Entity Domain model
//
//Master
public class School
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}

//Details
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public float Age { get; set; }

[ForeignKey("School")]
[Display(Name="School Name")]
public int SchId { get; set; }
public virtual School School { get; set; }
}

In the master class School, we indicate one to many relationships between master and details using:

public virtual ICollection Students { get; set; }

And details class Student has a foreign key relationship of master class School.

[ForeignKey("<master_class_name>")]
[Display(Name="School Name")]
public int SchId { get; set; }
public virtual School School { get; set; }  

Now, we have to create a db context class using Entity Framework before creating Controller for CRUD operations. For that, create a class ApplicationDbContext that inherits IdentityDbContext.

using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace Rakib33_EFCodeFirst.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class.
    public class ApplicationUser : IdentityUser
    {
        public string Description { get; set; }
    }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("CodeFirstConString")
        {
        }
        public IDbSet<School> Schools { get; set; }
        public IDbSet<Student> Students { get; set; }
    }
  }

CodeFirstConString is our database connection string name in web.config.

Schools and Students are our master details class db object.

Creating the Controller

Right click on Controllers folder from Project Solution then select Add->Controller. Then, add Scaffold popup box will appear. Select MVC 5 Controller with views, using Entity Framework so that it automatically creates the corresponding view page.

Click ok.

Now give a controller name in controller name section, select School Model class and ApplicationDbContext as Data context.Click Add button. SchoolController will be created with its view. Do the same process for Student Controller. Run the application and see the url - it looks like http://localhost:1055/. You can see School and Student page by changing the url like http://localhost:1055/School or http://localhost:1055/Student. Now add some data in School and Student from Create option. Our database and table will created. To see database and table, go to View->Server Explorer->Data Connection and see:

Code First Migration

If we wanted to make any change to our model class, we have to do code first migration. I am adding an extra field Email in our Student class. So Student class looks like:

public class Student {
       public int Id { get; set; }
       public string Name { get; set; }
       public float Age { get; set; }

       //newly added
       public string Email { get; set; }

       [ForeignKey("School")]
       [Display(Name="School Name")]
       public int SchId { get; set; }
       public virtual School School { get; set; }
    }

Now go to TOOLS->Library Package Manager-> Package Manager Console. Package Manager Console box will appear. Run Enable Migration command.

PM> enable-migrations

After exciting enable-migrations command, a folder named Migrations will be created in your project with Configuration.cs class and an InitialCreate.cs class. Open Configuration.cs class and do change the Configuration constructor method as:

public Configuration()
       {
           AutomaticMigrationsEnabled = true;
           AutomaticMigrationDataLossAllowed = false;
           ContextKey = "Rakib33_EFCodeFirst.Models.ApplicationDbContext";
       }

For automatic migration, set AutomaticMigrationsEnabled as true and to prevent data loss while model changes, set AutomaticMigrationDataLossAllowed as false.

The Configuration of Code First AutoMigration is done. Go to Package Manager Console and run update database command as below:

PM> Update-Database -Verbose

The Email field is added in our student table.See Student table from Server Explorer.

The next time, whenever you have to make any changes in your Domain model, simply run Update-Database or Update-Database -Verbose from Package Manager Console.

Conclusion

Hope it will be helpful for you to learn Code First approach with Automatic Migrations. So don’t forget to give any feedback.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here