How to use a repository pattern in ASP.NET MVC?
Step 1: Create web application
Open Visual Studio
Create new project
Â
- File->New->Project->web->Asp.Net web Application (.Net framework)
Provide name and Location and Click on next.
Select the Basic template (MVC) and Click on ok.
Step 2: Create a table
Open Microsoft SQL server management studio.
Select the Database and Create a table.
Â
1.2 student table
Â
Step 3: Connect with the database with (Db First Approach).
Open solution explorer and Add new Data Model.
- Add->New Item->Data->Ado.net Data Entity Model.
Connect with the database and add a table.
- EF Designer from database->Add properties->Select table->Connect
Â
1.3 Establish Connection for SQL server.
Â
Step 4: Create a Repository for Employee
Create Repository folder inside the project
Â
- Create a Repository and Interface inside the Repository folder.
IStudentRepository.cs
Â
usingSystem.Collections.Generic;
namespaceRepository.Models
{
publicinterfaceIStudentRepository
{
IEnumerableGetStudents();
student GetStudentById(ints_id);
voidInsertStudent(student s);
voidUpdateStudent(student s);
voidDeleteStudent(ints_id);
voidsave();
}
}
StudentRepository.cs
StudentRepositoryimplementsIStudentRepository
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
namespaceRepository.Models
{
publicclassStudentRepository :IStudentRepository
{
private demoEntities2 _context;
publicStudentRepository(demoEntities2 context)
{
this._context = context;
}
publicIEnumerableGetStudents()
{
return _context.students.ToList();
}
public student GetStudentById(ints_id)
{
return _context.students.Find(s_id);
}
publicvoidInsertStudent(student s)
{
_context.students.Add(s);
}
publicvoidUpdateStudent(student s)
{
_context.Entry(s).State = System.Data.Entity.EntityState.Modified;
}
publicvoidDeleteStudent(ints_id)
{
student s = _context.students.Find(s_id);
_context.students.Remove(s);
}
publicvoidsave()
{
_context.SaveChanges();
}
publicvoidDispose()
{
thrownewNotImplementedException()
}
}
}
Step 5: Call Repository from Controller.
Add new controller
- Add->new Item->Controller->MVC5-Controller Empty
Controller Interact with StudentRepository by creating Reference of IStudentRepository
StudentController.cs
Â
usingDemo.Models;
usingSystem.Linq;
usingSystem.Web.Mvc;
namespaceDemo.Controllers
{
publicclassStudentController : Controller
{
// GET: Student
privateIStudentRepositoryinterfaceobj;
publicStudentController()
{
this.interfaceobj = newStudentRepository(new demoEntities2());
}
// GET: Student
publicActionResultIndex()
{
var data = from m ininterfaceobj.GetStudents() select m;
return View(data);
}
publicActionResultDetailStudent(int id)
{
student s = interfaceobj.GetStudentById(id);
return View(s);
}
publicActionResultCreateStudent()
{
returnView();
}
[HttpPost]
publicActionResultCreateStudent(student s)
{
interfaceobj.InsertStudent(s);
interfaceobj.save();
returnRedirectToAction("Index");
}
publicActionResultUpdateStudent(int id)
{
student s = interfaceobj.GetStudentById(id);
return View(s);
}
[HttpPost]
publicActionResultUpdateStudent(int id, student s)
{
interfaceobj.UpdateStudent(s);
interfaceobj.save();
returnRedirectToAction("Index");
}
publicActionResultDeleteStudent(int id)
{
student s = interfaceobj.GetStudentById(id);
return View(s);
}
[HttpPost]
publicActionResultDeleteStudent(int id, student s)
{
interfaceobj.DeleteStudent(id);
interfaceobj.save();
returnRedirectToAction("Index");
}
}
}
Â
Step 5: Add View.
Â
Add View for Index, CreateStudent, DetailStudent, DeleteStudent
Â
Index.cs
@model IEnumerable
@{
ViewBag.Title = "Index";
}Index
@Html.ActionLink("Create New", "CreateStudent")
@foreach (var item in Model) {
}
 |
 |
@Html.DisplayNameFor(model => model.s_id) | Â |
@Html.DisplayNameFor(model => model.s_name) | Â |
@Html.DisplayNameFor(model => model.s_lastname) | Â |
@Html.DisplayNameFor(model => model.s_bday) | Â | Â | Â |
---|
 |
@Html.DisplayFor(modelItem => item.s_id) | Â |
@Html.DisplayFor(modelItem => item.s_name) | Â |
@Html.DisplayFor(modelItem => item.s_lastname) | Â |
@Html.DisplayFor(modelItem => item.s_bday) | Â |
@Html.ActionLink("Edit", "UpdateStudent", new { id=item.s_id }) |
@Html.ActionLink("Details", "DetailStudent", new { id=item.s_id }) |
@Html.ActionLink("Delete", "DeleteStudent", new { id=item.s_id }) | Â |
Â
CreateStudent.cs
@model Demo.Models.student
@{
ViewBag.Title = "CreateStudent";
}CreateStudent
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
student
@Html.LabelFor(model =>model.s_name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model =>model.s_name, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model =>model.s_lastname, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model =>model.s_lastname, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model =>model.s_bday, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model =>model.s_bday, new { htmlAttributes = new { @class = "form-control" } })
}
@Html.ActionLink("Back to List", "Index")
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Â
note:
Asp.net MVC provide Template [List, add, edit, delete] for View. For adding View Right Click on the method and Add View. Select Template and add Model class.
In RouteConfig.cs file change the name of controller [Home->Student]
Step 7: Build and Run Project
Build and Run the application.
1.4 Student View page