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.
It will open a new dialog where you can choose different types of project. Choose MVC as the project and click on OK.
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:
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.
- namespace EmployeeManagement.Models
- {
- public class Employee
- {
- [Key]
- public int Id { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
- public string Age { get; set; }
-
- public string Address { get; set; }
-
- }
- }
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.
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.
And finally your
EmployeeContext class looks like the following:
- using System.Data.Entity;
-
- namespace EmployeeManagement.Models
- {
- public class EmployeeContext :DbContext
- {
- public EmployeeContext():base("myconnection")
- {
- }
-
- public DbSet<Employee> Employees { get; set; }
- }
- }
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”
IRepository.cs
- using System;
- using System.Collections.Generic;
-
- namespace EmployeeManagement.Repository
- {
- public interface IRepository<T> where T: class
- {
- IEnumerable<T> GetAll();
- T GetById(object Id);
- void Insert(T obj);
- void Update(T obj);
- void Delete(Object Id);
- void Save();
- }
- }
Repository.cs - using EmployeeManagement.Models;
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
-
- namespace EmployeeManagement.Repository
- {
- public class Repository<T> : IRepository<T> where T : class
- {
- private EmployeeContext db;
- private DbSet<T> dbSet;
-
- public Repository()
- {
- db = new EmployeeContext();
- dbSet = db.Set<T>();
- }
- public IEnumerable<T> GetAll()
- {
- return dbSet.ToList();
- }
-
- public T GetById(object Id)
- {
- return dbSet.Find(Id);
- }
-
- public void Insert(T obj)
- {
- dbSet.Add(obj);
- }
- public void Update(T obj)
- {
- db.Entry(obj).State = EntityState.Modified;
- }
- public void Delete(object Id)
- {
- T getObjById = dbSet.Find(Id);
- dbSet.Remove(getObjById);
- }
- public void Save()
- {
- db.SaveChanges();
- }
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (this.db != null)
- {
- this.db.Dispose();
- this.db = null;
- }
- }
- }
-
-
- }
- }
Adding a Controller To add new controller, right click on
Controller folder and click on
Add and choose
Controller.
Give the name of controller as “
EmployeeController” and choose
OK. And made change in code like the following code snippet:
- using EmployeeManagement.Models;
- using EmployeeManagement.Repository;
- using System.Web.Mvc;
-
- namespace EmployeeManagement.Controllers
- {
- public class EmployeeController : Controller
- {
- private IRepository<Employee> _repository = null;
- public EmployeeController()
- {
- this._repository = new Repository<Employee>();
- }
-
- public ActionResult Index()
- {
- var employees = _repository.GetAll();
- return View(employees);
- }
-
- [HttpGet]
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _repository.Insert(employee);
- _repository.Save();
- return RedirectToAction("Index");
- }
- else
- {
- return View(employee);
- }
- }
-
-
- public ActionResult Edit(int Id)
- {
- var employee = _repository.GetById(Id);
- return View(employee);
- }
-
- [HttpPost]
- public ActionResult Edit(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _repository.Update(employee);
- _repository.Save();
- return RedirectToAction("Index");
- }
- else
- {
- return View(employee);
- }
- }
-
- public ActionResult Details(int Id)
- {
- var employee = _repository.GetById(Id);
- return View(employee);
- }
- public ActionResult Delete(int Id)
- {
- var employee = _repository.GetById(Id);
- return View(employee);
- }
-
- [HttpPost, ActionName("Delete")]
- public ActionResult DeleteConfirmed(int Id)
- {
- var employee = _repository.GetById(Id);
- _repository.Delete(Id);
- _repository.Save();
- return RedirectToAction("Index");
- }
- }
- }
Adding View So, time to add view for every ActionResult. To add view, right click on ActionResult
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:
For creating a new record.
For Editing the existing record.
For viewing (view) single Employee Details.
For Deleting and Delete Confirmation.
So, finally all the views have been added and it will look like the following screenshot:
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:
- <connectionStrings>
- <add name="DefaultConnection" connectionString="server=Mukesh-PC; Database=TestEmployee; User Id=sa; Password=password;" providerName="System.Data.SqlClient" />
- </connectionStrings>
When you run the application using
F5 you will see the following result.
When you view the result.
When you create a new Record.
When you Edit the Record.
When you see the record on one employee.
When you are ready delete a record.
Thanks for reading this article. Hope you enjoyed it. Waiting for your feedback on this.