ASP.NET MVC Code First Approach With Repository Pattern

Today, I am going to explain a very interesting topic; “How to use Code First Approach in ASP.NET MVC with Generic Repository Pattern”. So, first I will explain what Code First approach is and why we use it and later I will explain you about Repository Pattern.

There are three approaches in Entity Framework to work with database and these are Database First, Model First and Code First. I always prefer to work with Code First approach.

Code First Approach

It is a part of Entity Framework which uses POCO [Plan Old CLR Object]. Basically it removes to write or doing some extra effort to write data access code. In the code first, firstly we create our model entity. It is our domain model. We only need to define our entity classes and rest of the task is done by Entity Framework.

Repository Pattern

It is used to create an abstraction layer between data access logic and business logic in the application. It has the responsibility to communicate with data access layer and get data and transfer it to business logic layer.

Create an ASP.NET MVC Project

Open Visual Studio 2015, Click on File, choose New and then choose Project. It will open a New Project Dialog. Inside the Installed Template, choose Visual C# and then choose Web. After that select ASP.NET Web Application and provide the proper name and click OK.

Web Application

It will open a new dialog where you can choose different types of project. Choose MVC as the project and click on OK.

MVC

It will take some time and create a new project for you. When you will see the project inside the solution explorer then you can see the following project structure:

solution explorer

So, project is ready.

Adding Model

To add a new model, right click on Model folder and choose Add and then select class. It will open a add new class dialog where you need to pass the model class name “Emloyee.cs” and click on OK.

Make some change in the class and add some Employee properties like this.

  1. namespace EmployeeManagement.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         [Key]  
  6.         public int Id { getset; }  
  7.         public string Name { getset; }  
  8.         public string Email { getset; }  
  9.         public string Age { getset; }  
  10.   
  11.         public string Address { getset; }  
  12.   
  13.     }  
  14. }  
When you will add [Key], it will give you an error, so here you need to mention the namespace for it. To fix this add using System.ComponentModel.DataAnnotations; as namespace.

Key

Now the time is to add one more domain model which is your Database context. So, add a new model named with “EmployeeContext.cs” and make code like this.

When you will inherit the DbContext with EmployeeContext.cs, you just need to add System.Data.Entity namespace.

DbContext

And finally your EmployeeContext class looks like the following:
  1. using System.Data.Entity;  
  2.   
  3. namespace EmployeeManagement.Models  
  4. {  
  5.     public class EmployeeContext :DbContext  
  6.     {  
  7.         public EmployeeContext():base("myconnection")  
  8.         {  
  9.         }  
  10.   
  11.         public DbSet<Employee> Employees { getset; }  
  12.     }  
  13. }  
Adding Repository

It is time to add Generic repository which performs our database operation. So, add a new folder named with “Repository” in the project and one interface named with “IRepository.cs” and a class “Repository.cs

Adding Repository

IRepository.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace EmployeeManagement.Repository  
  5. {  
  6.     public interface IRepository<T> where T: class  
  7.     {  
  8.         IEnumerable<T> GetAll();  
  9.         T GetById(object Id);  
  10.         void Insert(T obj);  
  11.         void Update(T obj);  
  12.         void Delete(Object Id);  
  13.         void Save();  
  14.     }  
  15. }  
Repository.cs
  1. using EmployeeManagement.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace EmployeeManagement.Repository  
  9. {  
  10.     public class Repository<T> : IRepository<T> where T : class  
  11.     {  
  12.         private EmployeeContext db;  
  13.         private DbSet<T> dbSet;  
  14.   
  15.         public Repository()  
  16.         {  
  17.             db = new EmployeeContext();  
  18.             dbSet = db.Set<T>();  
  19.         }  
  20.         public IEnumerable<T> GetAll()  
  21.         {  
  22.             return dbSet.ToList();  
  23.         }  
  24.          
  25.         public T GetById(object Id)  
  26.         {  
  27.             return dbSet.Find(Id);  
  28.         }  
  29.   
  30.         public void Insert(T obj)  
  31.         {  
  32.             dbSet.Add(obj);  
  33.         }  
  34.         public void Update(T obj)  
  35.         {  
  36.             db.Entry(obj).State = EntityState.Modified;  
  37.         }  
  38.         public void Delete(object Id)  
  39.         {  
  40.             T getObjById = dbSet.Find(Id);  
  41.             dbSet.Remove(getObjById);  
  42.         }  
  43.         public void Save()  
  44.         {  
  45.             db.SaveChanges();  
  46.         }  
  47.         protected virtual void Dispose(bool disposing)  
  48.         {  
  49.             if (disposing)  
  50.             {  
  51.                 if (this.db != null)  
  52.                 {  
  53.                     this.db.Dispose();  
  54.                     this.db = null;  
  55.                 }  
  56.             }  
  57.         }  
  58.   
  59.   
  60.     }  
  61. }  
Adding a Controller

To add new controller, right click on Controller folder and click on Add and choose Controller.

Adding a Controller

Give the name of controller as “EmployeeController” and choose OK.

EmployeeController

And made change in code like the following code snippet:
  1. using EmployeeManagement.Models;  
  2. using EmployeeManagement.Repository;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace EmployeeManagement.Controllers  
  6. {  
  7.     public class EmployeeController : Controller  
  8.     {  
  9.         private IRepository<Employee> _repository = null;  
  10.         public EmployeeController()  
  11.         {  
  12.             this._repository = new Repository<Employee>();  
  13.         }  
  14.   
  15.         public ActionResult Index()  
  16.         {  
  17.             var employees = _repository.GetAll();  
  18.             return View(employees);  
  19.         }  
  20.   
  21.         [HttpGet]  
  22.         public ActionResult Create()  
  23.         {  
  24.             return View();  
  25.         }  
  26.   
  27.         [HttpPost]  
  28.         public ActionResult Create(Employee employee)  
  29.         {  
  30.             if (ModelState.IsValid)  
  31.             {  
  32.                 _repository.Insert(employee);  
  33.                 _repository.Save();  
  34.                 return RedirectToAction("Index");  
  35.             }  
  36.             else  
  37.             {  
  38.                 return View(employee);  
  39.             }  
  40.         }  
  41.   
  42.   
  43.         public ActionResult Edit(int Id)  
  44.         {  
  45.             var employee = _repository.GetById(Id);  
  46.             return View(employee);  
  47.         }  
  48.   
  49.         [HttpPost]  
  50.         public ActionResult Edit(Employee employee)  
  51.         {  
  52.             if (ModelState.IsValid)  
  53.             {  
  54.                 _repository.Update(employee);  
  55.                 _repository.Save();  
  56.                 return RedirectToAction("Index");  
  57.             }  
  58.             else  
  59.             {  
  60.                 return View(employee);  
  61.             }  
  62.         }  
  63.   
  64.         public ActionResult Details(int Id)  
  65.         {  
  66.             var employee = _repository.GetById(Id);  
  67.             return View(employee);  
  68.         }  
  69.         public ActionResult Delete(int Id)  
  70.         {  
  71.             var employee = _repository.GetById(Id);  
  72.             return View(employee);  
  73.         }  
  74.   
  75.         [HttpPost, ActionName("Delete")]  
  76.         public ActionResult DeleteConfirmed(int Id)  
  77.         {  
  78.             var employee = _repository.GetById(Id);  
  79.             _repository.Delete(Id);  
  80.             _repository.Save();  
  81.             return RedirectToAction("Index");  
  82.         }  
  83.     }  
  84. }  
Adding View

So, time to add view for every ActionResult. To add view, right click on ActionResult

Adding View

It will open a new dialog to Add View. Here you can choose your model data, template [insert, delete, edit, select] and your layout also.

So, add all view like for Index [Select], Delete, Edit and Insert.

For Index ActionResult, where you will see all the records:

Index ActionResult

For creating a new record.

Create a new record

For Editing the existing record.

Edit the existing Record

For viewing (view) single Employee Details.

View Single Employee Details

For Deleting and Delete Confirmation.

add view

view

So, finally all the views have been added and it will look like the following screenshot:

view has been added

Run the project, It will create you database automatically because we are using Code First approach.

You need to pass connection string like the following code snippet:
  1. <connectionStrings>  
  2.    <add name="DefaultConnection" connectionString="server=Mukesh-PC; Database=TestEmployee; User Id=sa; Password=password;" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
explorer

When you run the application using F5 you will see the following result.

When you view the result.

view the result

When you create a new Record.

Create the new Record

When you Edit the Record.

Edit the Record

When you see the record on one employee.

see the record

When you are ready delete a record.

delete a record

Thanks for reading this article. Hope you enjoyed it. Waiting for your feedback on this.

 


Similar Articles