Introduction
This article will explain repository design pattern with ADO.Net in MVC from the database without using the entity framework. I am going to use ADO.Net for this article.
- CREATE TABLE [dbo].[Employee](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Position] [nvarchar](50) NULL,
- [Office] [nvarchar](50) NULL,
- [Age] [int] NULL,
- [Salary] [int] NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- /* TO GET ALL EMPLYEES AND GET EMPLOYEE BY ID*/
- create procedure spGetEmployee
- as
- begin
- select * from Employee
- end
- /* TO CREATE NEW EMPLOYEE*/
- create procedure spAddNew
- (
- @Name nvarchar(50),
- @Position nvarchar(50),
- @Office nvarchar(50),
- @Age int,
- @Salary int
- )
- as
- begin
- insert into Employee(Name,Position,Office,Age,Salary)
- values(@Name,@Position,@Office,@Age,@Salary)
- end
- /* TO UPDATE EMPLOYEE*/
- create procedure spUpdateEmployee
- (
- @Id int,
- @Name nvarchar(50),
- @Position nvarchar(50),
- @Office nvarchar(50),
- @Age int,
- @Salary int
- )
- as
- begin
- update Employee
- set Name=@Name,Position=@Position,Office=@Office,Age=@Age,Salary=@Salary
- where Id=@Id
- end
- /* TO DELETE EMPLOYEE*/
- create procedure spDeleteEmployee
- (
- @Id int
- )
- as
- begin
- delete from Employee where Id=@Id
- end
Step 2: Open Visual Studio with a version of your choice and create a new project with an appropriate name.

Step 3: Choose an "Empty" template, check MVC under "Add folders & core references", and click "Create".

Step 5: Right-click on the project “Add” folder name it Repository “Add” an interface IEmployee and “Add” class Name it MockEmployee.
IEmployee interface
- using RepositoryPatternWithADO.Net.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace RepositoryPatternWithADO.Net.Repository
- {
- public interface IEmployee
- {
- IList<Employee> GetEmployees();
- Employee GetEmployeeById(int? id);
- void InsertNew(Employee employee);
- void Update(Employee employee);
- void Delete(Employee employee);
- }
- }
MockEmployee Class
- using RepositoryPatternWithADO.Net.Models;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- namespace RepositoryPatternWithADO.Net.Repository
- {
- public class MockEmployee : IEmployee
- {
- private readonly string CS = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
- public IList<Employee> GetEmployees()
- {
- List<Employee> employees = new List<Employee>();
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetEmployee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- var employee = new Employee()
- {
- Id = Convert.ToInt32(rdr["Id"]),
- Name = rdr["Name"].ToString(),
- Position = rdr["Position"].ToString(),
- Office = rdr["Office"].ToString(),
- Age = Convert.ToInt32(rdr["Age"]),
- Salary = Convert.ToInt32(rdr["Salary"])
- };
- employees.Add(employee);
- }
- return (employees);
- }
- }
- public Employee GetEmployeeById(int? id)
- {
- Employee employee = new Employee();
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetEmployee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- employee.Id = Convert.ToInt32(rdr["Id"]);
- employee.Name = rdr["Name"].ToString();
- employee.Position = rdr["Position"].ToString();
- employee.Office = rdr["Office"].ToString();
- employee.Age = Convert.ToInt32(rdr["Age"]);
- employee.Salary = Convert.ToInt32(rdr["Salary"]);
- }
- return employee;
- }
- }
- public void InsertNew(Employee employee)
- {
- using (SqlConnection con = new SqlConnection(CS))
- {
- var cmd = new SqlCommand("spAddNew", con);
- con.Open();
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Name", employee.Name);
- cmd.Parameters.AddWithValue("@Position", employee.Position);
- cmd.Parameters.AddWithValue("@Office", employee.Office);
- cmd.Parameters.AddWithValue("@Age", employee.Age);
- cmd.Parameters.AddWithValue("@Salary", employee.Salary);
- cmd.ExecuteNonQuery();
- }
- }
- public void Update(Employee employee)
- {
- using (SqlConnection con = new SqlConnection(CS))
- {
- var cmd = new SqlCommand("spUpdateEmployee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Id", employee.Id);
- cmd.Parameters.AddWithValue("@Name", employee.Name);
- cmd.Parameters.AddWithValue("@Position", employee.Position);
- cmd.Parameters.AddWithValue("@Office", employee.Office);
- cmd.Parameters.AddWithValue("@Age", employee.Age);
- cmd.Parameters.AddWithValue("@Salary", employee.Salary);
- cmd.ExecuteNonQuery();
- }
- }
- public void Delete(Employee employee)
- {
- using (SqlConnection con = new SqlConnection(CS))
- {
- var cmd = new SqlCommand("spDeleteEmployee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Id", employee.Id);
- cmd.ExecuteNonQuery();
- }
- }
- }
- }
Step 6: Open on Web Config file and add database connection string.
- <connectionStrings>
- <add name="EmployeeContext" connectionString="data source=farhan; database=MvcDemo; integrated security=true;" providerName="System.Data.SqlClient"/>
- </connectionStrings>
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
Controller Class code
- using RepositoryPatternWithADO.Net.Models;
- using RepositoryPatternWithADO.Net.Repository;
- using System.Net;
- using System.Web.Mvc;
- namespace RepositoryPatternWithADO.Net.Controllers
- {
- public class HomeController : Controller
- {
- private readonly MockEmployee db = new MockEmployee();
- public ActionResult Index()
- {
- var employee = db.GetEmployees();
- return View(employee);
- }
- public ActionResult Details(int? id)
- {
- var employee = db.GetEmployeeById(id);
- return View(employee);
- }
- public ActionResult Create()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.InsertNew(employee);
- return RedirectToAction("Index", "Home");
- }
- return View();
- }
- [HttpGet]
- public ActionResult Edit(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var employee = db.GetEmployeeById(id);
- if (employee==null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit(Employee employee)
- {
- db.Update(employee);
- return RedirectToAction("Index", "Home");
- }
- [HttpGet]
- public ActionResult Delete(int? id)
- {
- if (id==null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var employee = db.GetEmployeeById(id);
- if (employee==null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- [HttpPost,ActionName("Delete")]
- public ActionResult ConfirmDelete(int id)
- {
- var employee = db.GetEmployeeById(id);
- db.Delete(employee);
- return RedirectToAction("Index","Home");
- }
- }
- }
Step 8: Right click on Index of ActionResult choose “Add View” and click on it. Now you will get another window which has default view name as ActionResult name. Checked Use a lay page and click on “Add”.
Index View
- @model IEnumerable<RepositoryPatternWithADO.Net.Models.Employee>
- @{
- ViewBag.Title = "Index";
- }
- <link href="@Url.Content("~/Content/DataTables/css/dataTables.bootstrap4.min.css")" rel="stylesheet" />
- <div style="margin-bottom:10px;">
- @Html.ActionLink("Create New", "Create", "Home", "", new { @class = "btn btn-sm btn-primary rounded-0" })
- </div>
- <h4 class="text-center text-uppercase">List of employees</h4>
- <table id="example" class="table table-bordered">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(m => m.Name)</th>
- <th>@Html.DisplayNameFor(m => m.Position)</th>
- <th>@Html.DisplayNameFor(m => m.Office)</th>
- <th>@Html.DisplayNameFor(m => m.Age)</th>
- <th>@Html.DisplayNameFor(m => m.Salary)</th>
- <th>Action(s)</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model)
- {
- <tr>
- <td>@item.Name</td>
- <td>@item.Position</td>
- <td>@item.Office</td>
- <td>@item.Age</td>
- <td>@item.Salary</td>
- <td>
- <a href="@Url.Action("Details","Home",new { id=item.Id})" class="btn btn-sm btn-primary"><i class="fa fa-eye"></i></a>
- <a href="@Url.Action("Edit","Home",new { id=item.Id})" class="btn btn-sm btn-info"><i class="fa fa-pencil-square"></i></a>
- <a href="@Url.Action("Delete","Home",new { id=item.Id})" class="btn btn-sm btn-danger"><i class="fa fa-trash-o"></i></a>
- </td>
- </tr>
- }
- </tbody>
- </table>
- <script src="@Url.Content("~/Scripts/jquery-3.4.1.min.js")"></script>
- <script src="@Url.Content("~/Scripts/DataTables/jquery.dataTables.min.js")"></script>
- <script src="@Url.Content("~/Scripts/DataTables/dataTables.bootstrap4.min.js")"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $('#example').DataTable();
- });
- </script>
Step 9: Now similarly right click on Details of ActionResult choose “Add View” and click on it. Now you will get another window which has default view name as ActionResult name. Checked Use a lay page and click on “Add”.
Details View
- @model RepositoryPatternWithADO.Net.Models.Employee
- @{
- ViewBag.Title = "Details";
- }
- <div class="card">
- <div class="card-header">
- <h5 class="text-uppercase">Employee Details</h5>
- </div>
- <div class="card-body">
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Position)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Position)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Office)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Office)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Age)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Age)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Salary)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Salary)
- </dd>
- </dl>
- @Html.ActionLink("Edit", "Edit", "Home", new { id = Model.Id }, new { @class = "btn btn-sm btn-info rounded-0" })
- @Html.ActionLink("Back to List", "Index", "", new { @class = "btn btn-sm btn-primary rounded-0" })
- </div>
- </div>
Step 10: Now click on Create of ActionResult choose “Add View” and click on it. Now you will get another window that has a default view name as ActionResult name. Checked Use a lay page and click on “Add”.
Create View
- @model RepositoryPatternWithADO.Net.Models.Employee
- @{
- ViewBag.Title = "Create";
- }
- <div class="card">
- <div class="card-header">
- <h5>New Employee</h5>
- </div>
- <div class="card-body">
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-group">
- @Html.LabelFor(m => m.Name)
- @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Name)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Position)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Office)
- @Html.TextBoxFor(m => m.Office, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Office)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Age)
- @Html.TextBoxFor(m => m.Age, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Age)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-sm btn-primary rounded-0">Submit</button>
- </div>
- }
- </div>
- </div>
Step 11: Right click on Edit of ActionResult choose “Add View” and click on it. Now you will get another window which has default view name as ActionResult name. Checked Use a lay page and click on “Add”.
Edit View
- @model RepositoryPatternWithADO.Net.Models.Employee
- @{
- ViewBag.Title = "Edit";
- }
- <div class="card">
- <div class="card-header">
- <h3>Edit Employee</h3>
- </div>
- <div class="card-body">
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- @Html.HiddenFor(m => m.Id)
- <div class="form-group">
- @Html.LabelFor(m => m.Name)
- @Html.EditorFor(m => m.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(m => m.Name)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.EditorFor(m => m.Position, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(m => m.Position)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Office)
- @Html.EditorFor(m => m.Office, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(m => m.Office)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Age)
- @Html.EditorFor(m => m.Age, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(m => m.Age)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.EditorFor(m => m.Salary, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-sm btn-primary rounded-0">Update</button>
- @Html.ActionLink("Back to List", "Index", "", new { @class = "btn btn-sm btn-primary rounded-0" })
- </div>
- }
- </div>
- </div>
Step 12: Right click on Delete of ActionResult choose “Add View” and click on it. Now you will get another window which has default view name as ActionResult name. Checked Use a lay page and click on “Add”.
Delete View
- @model RepositoryPatternWithADO.Net.Models.Employee
- @{
- ViewBag.Title = "Delete";
- }
- <div class="alert alert-danger">
- <h6>Are you sure you want to delete this?</h6>
- </div>
- <div class="card">
- <div class="card-header">
- <h5 class="text-uppercase"> Delete Emplyee Record</h5>
- </div>
- <div class="card-body">
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Position)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Position)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Office)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Office)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Age)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Age)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Salary)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Salary)
- </dd>
- </dl>
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-actions no-color">
- <input type="submit" value="Delete" class="btn btn-danger btn-sm rounded-0" />
- @Html.ActionLink("Back to List", "Index", "", new { @class = "btn btn-sm btn-primary rounded-0" })
- </div>
- }
- </div>
- </div>
Step 13: Build your project and run by pressing ctrl+F5

Summary
In this article, I have explained CURD (Create, Update, Read and Delete) operations using repository pattern and ADO.Net where I have created IEmployee interface and EmployeeMock class for database interaction like retrieving data, inserting data, updating existing data and deleting data from SQL database table.

IMAD AYOUBPosted May 26, 2020, 3:14 PM
Very nice and helpful. Thanks a lot.