Click here to Skip to main content
15,885,546 members
Articles / Web Development / HTML
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.12/5 (8 votes)
3 Nov 2015CPOL4 min read 22.8K   233   18   3
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:

Image 1

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:

Image 2

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:

Image 3

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:

Image 4

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

Image 5

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.

Image 6

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

Image 7

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.

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

C#
public virtual ICollection Students { get; set; }

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

C#
[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.

C#
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.

Image 8

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.

Image 9

Click ok.

Image 10

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:

Image 11

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:

C#
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

Image 12

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

Image 13

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

Image 14

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionMy remarks Pin
João Matos Silva3-Nov-15 23:37
professionalJoão Matos Silva3-Nov-15 23:37 
AnswerRe: My remarks Pin
Rakibul Islam 336-Nov-15 18:45
professionalRakibul Islam 336-Nov-15 18:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.