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

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

0.00/5 (No votes)
10 Nov 2014 2  
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:

//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...

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.

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

//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.

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.

<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

Creates the Configuration class inside Migrations folder.

2. Add the Property to the Employee Model

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

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

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