Background
There are many open source ORM to map the classes to the databases but now in this article we will learn about Dapper ORM. We can consider it as the king of ORM. In this article we will demonstrate Dapper ORM by implementing CRUD operations in MVC with step by step approach. I have written this article focusing on beginners so they can understand the basics of Dapper ORM. Please read my previous article using the following links to understand the basics about MVC:
So let us understand in brief about Dapper ORM
What is Dapper ?
Dapper is the Open source ORM which is used to map Microsoft platform .NET classes to the database.
Step 1 : Create an MVC Application.
Now let us start with a step by step approach from the creation of simple MVC application as in the following:
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
- As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application whose Solution Explorer will look like the following:
Step 2 : Add The Reference of Dapper ORM into Project.
Now next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
- Right click on Solution ,find Manage NuGet Package manager and click on it.
- After as shown into the image and type in search box "dapper".
- Select Dapper as shown into the image .
- Choose version of dapper library and click on install button.
After installing the Dapper library, it will be added into the References of our solution explorer of MVC application as:
I hope you have followed the same steps and installed dapper library.
Step 3: Create Model Class.
Now let us create the model class named EmpModel.cs by right clicking on model folder as in the following screenshot:
Note: It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.
EmpModel.cs class code snippet:
- public class EmpModel
- {
- [Display(Name = "Id")]
- public int Empid { get; set; }
-
- [Required(ErrorMessage = "First name is required.")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "City is required.")]
- public string City { get; set; }
-
- [Required(ErrorMessage = "Address is required.")]
- public string Address { get; set; }
-
- }
In the above model class we have added some validation on properties with the help of DataAnnotations.
Step 4 : Create Controller.
Now let us add the MVC 5 controller as in the following screenshot:
After clicking on
Add button it will show the following window. Now specify the
Controller name as
Employee with suffix
Controller as in the following screenshot:
Note: The controller name must be having suffix as 'Controller' after specifying the name of controller.
After clicking on Add button controller is created with by default code that support CRUD operations and later on we can configure it as per our requirements.
Step 5 : Create Table and Stored procedures.
Now before creating the views let us create the table name
Employee in database according to our model fields to store the details:
I hope you have created the same table structure as shown above. Now create the stored procedures to insert, update, view and delete the details as in the following code snippet:
To Insert Records
- Create procedure [dbo].[AddNewEmpDetails]
- (
- @Name varchar (50),
- @City varchar (50),
- @Address varchar (50)
- )
- as
- begin
- Insert into Employee values(@Name,@City,@Address)
- End
To View Added Records
- CREATE Procedure [dbo].[GetEmployees]
- as
- begin
- select Id as Empid,Name,City,Address from Employee
- End
To Update Records
- Create procedure [dbo].[UpdateEmpDetails]
- (
- @EmpId int,
- @Name varchar (50),
- @City varchar (50),
- @Address varchar (50)
- )
- as
- begin
- Update Employee
- set Name=@Name,
- City=@City,
- Address=@Address
- where Id=@EmpId
- End
To Delete Records
- Create procedure [dbo].[DeleteEmpById]
- (
- @EmpId int
- )
- as
- begin
- Delete from Employee where Id=@EmpId
- End
Step 6: Create Repository class.
Now create Repository folder and Add EmpRepository.cs class for database related operations, after adding, the solution explorer will look like the following screenshot:
Now create methods in EmpRepository.cs to handle the CRUD operation as in the following code snippet:
EmpRepository.cs
- public class EmpRepository
- {
- public SqlConnection con;
-
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
- con = new SqlConnection(constr);
-
- }
-
- public void AddEmployee(EmpModel objEmp)
- {
-
-
- try
- {
- connection();
- con.Open();
- con.Execute("AddNewEmpDetails", objEmp, commandType: CommandType.StoredProcedure);
- con.Close();
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
-
- }
-
- public List<EmpModel> GetAllEmployees()
- {
- try
- {
- connection();
- con.Open();
- IList<EmpModel> EmpList = SqlMapper.Query<EmpModel>(
- con, "GetEmployees").ToList();
- con.Close();
- return EmpList.ToList();
- }
- catch (Exception)
- {
-
- throw;
- }
- }
-
-
- public void UpdateEmployee(EmpModel objUpdate)
- {
- try
- {
- connection();
- con.Open();
- con.Execute("UpdateEmpDetails", objUpdate, commandType: CommandType.StoredProcedure);
- con.Close();
- }
- catch (Exception)
- {
-
- throw;
- }
-
- }
-
- public bool DeleteEmployee(int Id)
- {
- try
- {
- DynamicParameters param = new DynamicParameters();
- param.Add("@EmpId", Id);
- connection();
- con.Open();
- con.Execute("DeleteEmpById", param, commandType: CommandType.StoredProcedure);
- con.Close();
- return true;
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
- }
- }
Note
- In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
- Log the exception in database or text file as per you convenienc , since in the article I have not implemented it .
Step 7: Create Methods into the EmployeeController.cs file.
Now open the EmployeeController.cs and create the following action methods:
- public class EmployeeController : Controller
- {
-
-
- public ActionResult GetAllEmpDetails()
- {
- EmpRepository EmpRepo = new EmpRepository();
- return View(EmpRepo.GetAllEmployees());
- }
-
- public ActionResult AddEmployee()
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult AddEmployee(EmpModel Emp)
- {
- try
- {
- if (ModelState.IsValid)
- {
- EmpRepository EmpRepo = new EmpRepository();
- EmpRepo.AddEmployee(Emp);
-
- ViewBag.Message = "Records added successfully.";
-
- }
-
- return View();
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult EditEmpDetails(int id)
- {
- EmpRepository EmpRepo = new EmpRepository();
- return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id));
-
- }
-
-
- [HttpPost]
- public ActionResult EditEmpDetails(int id, EmpModel obj)
- {
- try
- {
- EmpRepository EmpRepo = new EmpRepository();
-
- EmpRepo.UpdateEmployee(obj);
-
- return RedirectToAction("GetAllEmpDetails");
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult DeleteEmp(int id)
- {
- try
- {
- EmpRepository EmpRepo = new EmpRepository();
- if (EmpRepo.DeleteEmployee(id))
- {
- ViewBag.AlertMsg = "Employee details deleted successfully";
-
- }
- return RedirectToAction("GetAllEmpDetails");
- }
- catch
- {
- return RedirectToAction("GetAllEmpDetails");
- }
- }
- }
Step 8: Create Views.
Create the Partial view to Add the employees
To create the Partial View to add Employees, right click on ActionResult method and then click
Add view. Now specify the view name, template name and model class in EmpModel.cs and click
Add button as in the following screenshot:
After clicking on Add button it generates the strongly typed view whose code is given below:
AddEmployee.cshtml
- @
- model CRUDUsingMVC.Models.EmpModel@ using(Html.BeginForm()) {@
- Html.AntiForgeryToken()
-
- < div class = "form-horizontal" >
- < h4 > Add Employee < /h4> < div > @Html.ActionLink("Back to Employee List", "GetAllEmpDetails") < /div> < hr / > @Html.ValidationSummary(true, "", new {@
- class = "text-danger"
- })
-
-
- < div class = "form-group" > @Html.LabelFor(model => model.Name, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.Name, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.Name, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" > @Html.LabelFor(model => model.City, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.City, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.City, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" > @Html.LabelFor(model => model.Address, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.Address, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.Address, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" >
- < div class = "col-md-offset-2 col-md-10" >
- < input type = "submit"
- value = "Save"
- class = "btn btn-default" / >
- < /div> < /div> < div class = "form-group" >
- < div class = "col-md-offset-2 col-md-10"
- style = "color:green" > @ViewBag.Message
-
- < /div> < /div> < /div>
-
- } < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> < script src = "~/Scripts/jquery.validate.min.js" > < /script> < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" > < /script>
To View Added Employees
To view the employee details let us create the partial view named GetAllEmpDetails:
Now click on add button, it will create GetAllEmpDetails.cshtml strongly typed view whose code is given below:
GetAllEmpDetails.CsHtml
- @model IEnumerable < CRUDUsingMVC.Models.EmpModel >
-
- < p > @Html.ActionLink("Add New Employee", "AddEmployee") < /p>
-
- < table class = "table" >
- < tr >
-
- < th > @Html.DisplayNameFor(model => model.Name) < /th> < th > @Html.DisplayNameFor(model => model.City) < /th>
- < th > @Html.DisplayNameFor(model => model.Address) < /th> < th > < /th> < /tr>
-
- @foreach(var item in Model)
- {
- @Html.HiddenFor(model => item.Empid)
- < tr >
-
- < td > @Html.DisplayFor(modelItem => item.Name) < /td>
- < td > @Html.DisplayFor(modelItem => item.City) < /td>
- < td > @Html.DisplayFor(modelItem => item.Address) < /td>
- < td > @Html.ActionLink("Edit", "EditEmpDetails", new {
- id = item.Empid
- }) | @Html.ActionLink("Delete", "DeleteEmp", new {
- id = item.Empid
- }, new {
- onclick = "return confirm('Are sure wants to delete?');"
- })
- < /td>
- < /tr>
-
- }
-
- < /table>
To Update Added Employees
Follow the same procedure and create EditEmpDetails view to edit the employees. After creating the view the code will be like the following:
EditEmpDetails.cshtml
- @model CRUDUsingMVC.Models.EmpModel
-
-
- @ using(Html.BeginForm()) {@
- Html.AntiForgeryToken()
-
- < div class = "form-horizontal" >
- < h4 > Update Employee Details < /h4> < hr / >
- < div > @Html.ActionLink("Back to Details", "GetAllEmployees") < /div> < hr / > @Html.ValidationSummary(true, "", new {@
- class = "text-danger"
- })@ Html.HiddenFor(model => model.Empid)
-
- < div class = "form-group" > @Html.LabelFor(model => model.Name, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.Name, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.Name, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" > @Html.LabelFor(model => model.City, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.City, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.City, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" > @Html.LabelFor(model => model.Address, htmlAttributes: new {@
- class = "control-label col-md-2"
- }) < div class = "col-md-10" > @Html.EditorFor(model => model.Address, new {
- htmlAttributes = new {@
- class = "form-control"
- }
- })@ Html.ValidationMessageFor(model => model.Address, "", new {@
- class = "text-danger"
- }) < /div> < /div>
-
- < div class = "form-group" >
- < div class = "col-md-offset-2 col-md-10" >
- < input type = "submit"
- value = "Update"
- class = "btn btn-default" / >
- < /div> < /div> < /div>
- } < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> < script src = "~/Scripts/jquery.validate.min.js" > < /script> < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" > < /script>
Step 9 : Configure Action Link to
Edit and delete the records as in the following figure:
The above ActionLink I have added in GetAllEmpDetails.CsHtml view because from there we will delete and update the records.
Step 10: Configure RouteConfig.cs to set default action as in the following code snippet:
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
- );
- }
- }
From the above RouteConfig.cs the default action method we have set is AddEmployee. It means that after running the application the AddEmployee view will be executed first.
Now after adding the all model, views and controller our solution explorer will be like the following screenshot:
Step 11: Run the Application
Now run the application the AddEmployee view appears as in the following screenshot
Click on save button, the model state validation will fire, as per validation we have set into the EmpModel.cs class:
Now enter the details and on clicking save button. The records get added into the database and the following message appears.
Now click on
Back to Employee List hyperlink, it will be redirected to employee details grid as in the following screenshot:
Now similar to above screenshot, add another record, then the list will be as in the following screenshot:
Now click on
Edit button of one of the record, then it will be redirected to Edit view as in the following screenshot:
Now click on Update button, on clicking, the records will be updated into the database. Click
Back to Details hyperlink then it will be redirected to the Employee list table with updated records as in the following screenshot:
Now click on delete button for one of the records, then the following confirmation box appears (we have set configuration in ActionLink).
Now click on
OK button, then the updated Employee list table will be like the following screenshot:
From the preceding examples we have learned how to implement CRUD operations in ASP.NET MVC using Dapper ORM.
Note:
- Configure the database connection in the web.config file depending on your database server location.
- Download the Zip file of the sample application for a better understanding.
- Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
- This application is created completely focusing on beginners.
- In the Repository code we manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it, dapper will automatically handled.
- Log the exception in database or text file as per you convenience, since in this article I have not implemented it.
Summary
My next article explains the types of controllers in MVC. I hope this article is useful for all readers. If you have any suggestion please contact me.