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

Entity Framework Migrations enabled in Data Access Class Library used in MVC project

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 Nov 2014CPOL2 min read 33.7K   466   11   10
Migrations enabled in Class Library (Data Access Layer) and the same is referenced to MVC ProjectNo need to maintain the Data Access and Model classes in the MVC Project. We can have separate Class library for Model and Data Access and have migrations enabled in Data Access where DbContext resides.

Introduction

This article is about maintaining the Migrations in Data Access Class Library, where the DbContext class resides and Model as separate Library and use in MVC Project.

Background

So far, I have been looking into MVC articles which will maintain the migrations (db changes) of model in MVC projects itself. So I thought of explaining how to maintain the migrations in Data Access Library instead of having migrations in MVC Project.

Let's Proceed with an Example

Create a Empty Solution in Visual Studio.

Note: I am creating this project in Visual Studio 2010 SP1.

Empty Solution

Add two class library projects to the Empty Solution. Just like below for these two:

  1. For Model
  2. For Data Access (Using the basic data access not using any pattern)

Class Library projects

Solution

Add a simple class called Employee to the Model Class Library:

C#
//Employee Class 
public class Employee
 {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
 }

Add the Context class to the Data class Library, but before that reference the Entity Framework to the Data Project using the nuget package manager console.

In the Nuget Package Manager Console, select the project as MyProject.Data.

Tools --> Nuget Package manager -- Package Manager Console

To install a nuget package for a project, use the following command...

C#
install-package EntityFramework

...after installing.

Add a simple DbContext class to Data class library, please add the model class library as reference to Data class Library.

C#
//Simple DbContext Class 
public class SimpleDbContext : DbContext
    {
        public SimpleDbContext() :
            base("DefaultConnection")
        {
        }
        public DbSet<Employee> Employees { get; set; }
    }

I will explain about the migrations as we progress, but before that, add an ASP.NET MVC 4 Project to the Solution.

MVC

Solutions

Add Reference of the Model and Data to the MVC Project.

In the Models folder, add the EmployeeViewModel as shown below:

C#
//EmployeeViewModel Class 
public class EmployeeViewModel
 {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
 }

Add an empty EmployeeController class to Controller folder.

C#
public class EmployeeController : Controller
{        
 public ViewResult Index()
        {
            using (var db = new SimpleDbContext())
            {
                var model = db.Employees.Select(e => new EmployeeViewModel
                {
                    Id = e.Id,
                    FirstName = e.FirstName,
                    LastName = e.LastName
                }).ToList();

                return View(model);
            }
        }

        public ViewResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(EmployeeViewModel model)
        {
            using (var db = new SimpleDbContext())
            {
                db.Employees.Add(new Employee
                {
                    Id = model.Id,
                    FirstName = model.FirstName,
                    LastName = model.LastName
                });
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        public ViewResult Edit(int Id)
        {
            using (var db = new SimpleDbContext())
            {
                var model = db.Employees.Where(x => x.Id == Id).Select(e => new EmployeeViewModel
                {
                    Id = e.Id,
                    FirstName = e.FirstName,
                    LastName = e.LastName
                }).First();

                return View(model);
            }
        }

        [HttpPost]
        public RedirectToRouteResult Edit(EmployeeViewModel model)
        {
            using (var db = new SimpleDbContext())
            {
                var employee = db.Employees.First(x => x.Id == model.Id);
                employee.FirstName = model.FirstName;
                employee.LastName = model.LastName;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
}

Add the build in template views for the above Controller Actions.

Add the HTML Action for Employee controller in _Layout.cshtml.

C#
<li>@Html.ActionLink("Employee", "Index", "Employee")</li>

Run the application. Add some employee to the DB using the UI.

List

Now, I want to display the Date Of Joining in Employee List. For this, I have to follow the steps below:

1. Enable Migrations

Open Package manager console. Make sure the MVC project is startup project in solution. Select Data Class Library in the project. Run the following command:

Enable-Migrations

Image 7

Creates the Configuration class inside Migrations folder.

2. Add the Property to the Employee Model

C#
public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DOJ { get; set; }
    }

Build the Model Project.

3. Add Migration

Image 8

C#
Add-Migration AddedDOJToEmployee

Migration will create a class with changes to the DB, class file will autogenerated No_MigrationName.cs.

For the above scenario:

201411102029538_AddedDOJTOEmployee.cs

If we have multiple migrations, we can rollback to specific migration by its name.

4. Update Database

Run:

PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201411102029538_AddedDOJToEmployee].
Applying code-based migration: 201411102029538_AddedDOJToEmployee.
Running Seed method.
PM> 

For any changes to the model, please follow the above two steps.

5. Modify the EmployeeViewModel to Accommodate DOJ

6. Update the Controller and Views

7. Run the Application

Image 9

Image 10

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
India India
Just a Developer.
Don't know when I will get perfection

Comments and Discussions

 
Questiongood article, thanks. Pin
bernie.ning13-Feb-18 22:55
bernie.ning13-Feb-18 22:55 
QuestionYour Tutorial Is Miss Key Parts Of Informaiton Pin
Member 1232693214-Feb-16 13:39
Member 1232693214-Feb-16 13:39 
GeneralMy vote of 5 Pin
ashish68923-Jun-15 21:41
professionalashish68923-Jun-15 21:41 
QuestionImage problem Pin
demir vahap10-Nov-14 22:59
professionaldemir vahap10-Nov-14 22:59 
AnswerRe: Image problem Pin
Valentino_Lokesh10-Nov-14 23:19
Valentino_Lokesh10-Nov-14 23:19 
GeneralRe: Image problem Pin
Valentino_Lokesh10-Nov-14 23:22
Valentino_Lokesh10-Nov-14 23:22 
GeneralRe: Image problem Pin
Valentino_Lokesh10-Nov-14 23:26
Valentino_Lokesh10-Nov-14 23:26 
GeneralRe: Image problem Pin
Its - Andy10-Nov-14 23:51
Its - Andy10-Nov-14 23:51 
GeneralRe: Image problem Pin
Valentino_Lokesh11-Nov-14 0:13
Valentino_Lokesh11-Nov-14 0:13 
GeneralRe: Image problem Pin
Nelek11-Nov-14 0:26
protectorNelek11-Nov-14 0:26 

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.