CRUD With Dapper Documentation2
CRUD With Dapper Documentation2
1. Project Setup
2. Database Setup
USE EmployeeDB;
Name NVARCHAR(100),
Age INT,
Department NVARCHAR(50),
);
Stored Procedures
You will need several stored procedures for various operations like
fetching data, inserting, updating, soft-deleting, and searching employees.
Here are the stored procedures you should create.
@PageNumber INT,
@PageSize INT
AS
BEGIN
SELECT *
FROM Employees
WHERE IsDeleted = 0
ORDER BY Id
END;
@Name NVARCHAR(100),
@Age INT,
@Department NVARCHAR(50)
AS
BEGIN
END;
@Id INT,
@Name NVARCHAR(100),
@Age INT,
@Department NVARCHAR(50)
AS
BEGIN
UPDATE Employees
WHERE Id = @Id;
END;
@Id INT
AS
BEGIN
UPDATE Employees
SET IsDeleted = 1
WHERE Id = @Id;
END;
@SearchTerm NVARCHAR(100)
AS
BEGIN
SELECT *
FROM Employees
AND IsDeleted = 0;
END;
3. Model Setup
In your project, add a Models folder, and within it, create a file called
Employee.cs.
Employee.cs (Model)
using System;
namespace PracticeWeb.Models
4. Employee Repository
Create a folder called Repositories and add a file called
EmployeeRepository.cs. This file will contain all the methods for
interacting with the database using Dapper.
Updated EmployeeRepository.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using Dapper;
namespace CRUD.Models
parameters.Add("@PageNumber", pageNumber);
parameters.Add("@PageSize", pageSize);
parameters.Add("@SearchTerm", searchTerm);
using (var multi = db.QueryMultiple("GetPaginatedEmployees",
parameters, commandType: CommandType.StoredProcedure))
return
db.QuerySingleOrDefault<Employee>("spGetEmployeeById", new { Id =
id }, commandType: CommandType.StoredProcedure);
}
public void UpdateEmployee(Employee employee)
db.Execute("spSoftDeleteEmployee", new { Id = id },
commandType: CommandType.StoredProcedure);
return db.Query<Employee>("spGetEmployeesWithPagination",
commandType: CommandType.StoredProcedure);
}
}
5. Controller Setup
Updated EmployeeController.cs
using CRUD.Models;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CRUD.Controllers
ViewBag.TotalRecords = totalRecords;
ViewBag.PageSize = pageSize;
ViewBag.CurrentPage = page;
ViewBag.SearchTerm = searchTerm;
return View(employees);
return View();
[HttpPost]
if (ModelState.IsValid)
_employeeRepository.InsertEmployee(employee);
{
var employee = _employeeRepository.GetEmployeeById(id);
if (employee == null)
return HttpNotFound();
return View(employee);
[HttpPost]
if (ModelState.IsValid)
_employeeRepository.UpdateEmployee(employee);
return RedirectToAction("Index");
return View(employee);
_employeeRepository.SoftDeleteEmployee(id);
return RedirectToAction("Index");
}
1. Adding Bootstrap to the Project
First, make sure you have Bootstrap 5 added to your project. You can do
this by adding the Bootstrap CDN to your layout page.
This is the shared layout for all views, and we will include Bootstrap here:
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
css" rel="stylesheet" />
<style>
body {
background-color: #f8f9fa;
.navbar {
background-color: #343a40;
}
.navbar a {
h2 {
margin-top: 20px;
background-color: #f1f1f1;
.btn-custom {
background-color: #17a2b8;
color: white;
.btn-custom:hover {
background-color: #138496;
color: white;
.form-control, .btn {
margin-top: 10px;
</style>
</head>
<body>
<div class="container-fluid">
</div>
</nav>
<div class="container">
@RenderBody()
</div>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle
.min.js"></script>
</body>
</html>
Next, let's create the Index.cshtml file to list all employees, add a search
bar, and include pagination controls.
@model IEnumerable<CRUD.Models.Employee>
<div class="col-md-8">
</form>
</div>
</div>
</div>
<div class="table-responsive">
<thead class="table-primary">
<tr>
<th>Name</th>
<th>Age</th>
<th>Department</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>@employee.Name</td>
<td>@employee.Age</td>
<td>@employee.Department</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
<nav class="fixed-bottom mb-4">
<li class="page-item">
</li>
</li>
<li class="page-item">
</li>
}
</ul>
</nav>
The Create.cshtml view will contain the form to add a new employee.
Bootstrap's form classes are used to style the form.
Create.cshtml
@{
ViewBag.Title = "Create";
@model CRUD.Models.Employee
@using (Html.BeginForm())
<div class="mb-3">
</div>
<div class="mb-3">
<div class="mb-3">
</div>
This form will allow users to update existing employee details. The UI is
similar to the Create form, with Bootstrap styling.
Edit.cshtml
@{
ViewBag.Title = "Edit";
@model CRUD.Models.Employee
@using (Html.BeginForm())
<div class="mb-3">
</div>
<div class="mb-3">
</div>
<div class="mb-3">
</div>
You can add more custom styling by modifying the CSS section in the
layout file or by creating a separate CSS file. Here are some suggestions
to make the views more attractive:
body {
background-color: #e9ecef;
h2 {
margin-top: 20px;
color: #343a40;
text-transform: uppercase;
letter-spacing: 1px;
.table {
background-color: white;
vertical-align: middle;
width: 80px;
6. Bootstrap Icons
To make your UI more visually appealing, you can also add icons next to
buttons using Bootstrap Icons. Simply add the Bootstrap Icons CDN:
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-
icons.css" rel="stylesheet">
Then, in your buttons:
</a>
</a>
Explanation
Got it! Let's go line-by-line, explaining each word, why it’s used,
how it contributes to the flow of data, and what would happen if
certain parts were removed or done differently. I'll start with
EmployeeController.cs and then move on to
EmployeeRepository.cs and Employee.cs. This detailed
explanation will help you see the bigger picture of data flow
and the functionality of each line.
EmployeeController.cs
public class EmployeeController : Controller
public: This keyword makes the EmployeeController class
accessible from anywhere in the application.
class EmployeeController: Defines a class named
EmployeeController, which handles requests related to
employee operations.
Controller: EmployeeController inherits from the
Controller class, which is part of ASP.NET MVC. It provides
methods like View(), RedirectToAction(), and
HttpNotFound() that are used to handle user requests and
generate responses.
ViewBag.TotalRecords = totalRecords;
ViewBag.PageSize = pageSize;
ViewBag.CurrentPage = page;
ViewBag.SearchTerm = searchTerm;
ViewBag: A dynamic object in MVC used to pass data
from the controller to the view. It doesn’t need to be
strongly typed.
ViewBag.TotalRecords = totalRecords: Passes the
totalRecords value to the view. This will help the view in
rendering the total number of employees.
ViewBag.PageSize = pageSize: Passes the pageSize to
the view so that the view knows how many records to
display per page.
ViewBag.CurrentPage = page: Passes the page number
to the view, which will be used to display the current page.
ViewBag.SearchTerm = searchTerm: Passes the
searchTerm to the view to display the current search filter.
Data Flow:
Data retrieved from the repository (totalRecords,
pageSize, page, searchTerm) is passed to the view through
ViewBag. The view uses this data to show the paginated
list of employees with search functionality.
return View(employees);
return View(employees): Returns the view to the user
and passes the list of employees to it. This list will be
rendered on the front-end (HTML page).
Data Flow:
The employees data, which was retrieved from the
repository, is passed to the view for display.
Delete Method
public ActionResult Delete(int id)
{
_employeeRepository.SoftDeleteEmployee(id);
return RedirectToAction("Index");
}
public ActionResult Delete(int id): Accepts an id
parameter, which represents the employee to be deleted.
_employeeRepository.SoftDeleteEmployee(id): Calls
the SoftDeleteEmployee() method to mark the employee
as deleted without physically removing them from the
database.
return RedirectToAction("Index"): Redirects the user to
the employee list after deletion.
Data Flow:
The id flows from the controller to the repository. The
employee is marked as deleted, and the user is redirected
back to the employee list page.
o What It Does:
It returns a tuple containing two values:
A list of Employee objects
representing the retrieved employee
data for the current page.
The total number of employee records
in the database (used for pagination
calculations).
3. Populating the View with Retrieved Data
(index.cshtml):
The Index action method receives the results from
GetPaginatedEmployees.
It assigns the retrieved employee list (employees),
total records (totalRecords), current page number
(page), page size (pageSize), and search term
(searchTerm) to the ViewBag object.
Why: The ViewBag object is used to temporarily
pass data from the controller to the view.
The Index action then returns the index.cshtml
view.
The index.cshtml view uses the data from the
ViewBag to:
o Display the list of employees in a table.
o Create the pagination controls based on the
total number of records, current page, and
page size.
o If a search term was provided, it displays the
search term in the view.
4. User Interaction (Search Functionality within
index.cshtml):
The user enters a search term in the search form on
the index.cshtml page and submits the form.
5. Searching for Employees (Commented Out Option in
Controller):
Action Method (Commented Out): Search(string
searchTerm) (though commented out, it provides
context for the previous user interaction)
o This action method would have been called
when the user submits the search form, but it's
currently commented out.
o Why (Commented Out): This functionality is
likely replaced by using the search term within
GetPaginatedEmployees.
o Commented Out SP (Contextual): This action
method previously might have utilized the
spSearchEmployees stored procedure (also
commented out in the repository).
6. User Interaction (Clicking Buttons):
The user interacts with the buttons on the
index.cshtml page:
o "Add New Employee" button triggers a
navigation to the Create view for creating a
new employee.
o "Edit" link for a specific employee triggers
navigation to the Edit view for editing an
existing employee.
o "Delete" link for a specific employee triggers
deletion through the Delete action method.
7. Creating a New Employee:
Action Method Used:
o Clicking "Add New Employee" calls the Create
action method (public ActionResult Create())
o Why: This method handles displaying the initial
form for creating a new employee.
o The Create action then returns the
create.cshtml view, which provides the form for
entering new employee details.