Click here to Skip to main content
15,886,137 members
Articles / Web Development / HTML
Tip/Trick

Dapper.NET Sample with MVC 4- Add,Edit,Update,Delete

Rate me:
Please Sign up or sign in to vote.
4.64/5 (11 votes)
12 Aug 2014CPOL2 min read 94.8K   5.8K   14   13
Simple Dapper.NET Example with MVC

Download DapperExample-noexe.zip
Download Database_Script.zip
 

Introduction

This example is for Dapper.NET beginner , how to use Dapper.NET tool for Add,Edit,Update and Delete. As a Dapper.NET bigginer you can simply identyfy the steps to build simple MVC application with dapper. 

The sample included simple MVC 4 web application and one simple SQL Table. 

Background

Dapper.net is a simple ORM tool for .NET like Entity frame work.If you want get to know what is dapper.net you can reffer the code project article by .

Using the code

As I describe earlier, this is very simple MVC application to understand how to use dapper.Net. Her you can see the output of the application.

Image 1

 

Steps to be followed 

1. Create the DapperExample Visual Studio project using ASP.NET MVC 4 WebApplication(Empty) Category.
2. Create the Folder 'Dapper' inside the project.
3. Run the Database Script provided for create tblEmployee or Create simple table to connect with the application.
4. Create Model Class Employee inside the Model Folder.

C#
namespace DapperExample.Dapper
{
    public class Employee
    {
        public int EmpID { get; set; }

        public string EmpName { get; set; }

        public double EmpScore { get; set; }
    }
}

5. Use the Dapper.NET Framework to the project you have created using Package Manager consol in Visual Studio.
     Tools >> Library Package Manager >> Package Manager Console -->> PM  Install-Package Dapper
6. Create IEmployeeDashboard interface

C#
public interface IEmployeeDashBoard
    {
        List<employee> GetAll();
        Employee Find(int? id);
        Employee Add(Employee employee);
        Employee Update(Employee employee);
        void Remove(int id);
    }
</employee>

7. Implement the EmployeeDashBoard Class with all the operations. This Class should have the refferance to Dapper. 
 

C#
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperExample.Dapper
{
    public class EmployeeDashBoard : IEmployeeDashBoard
    {
        private IDbConnection _db = new SqlConnection("Data Source=CD-GLIYANAGE\\SQLEXPRESS; Database= Test; Integrated Security=True;");

        public List<employee> GetAll()
        {
            List < Employee > empList= this._db.Query<employee>("SELECT * FROM tblEmployee").ToList();
            return empList;
        }

        public Employee Find(int? id)
        {
            string query = "SELECT * FROM tblEmployee WHERE EmpID = " + id + "";
            return this._db.Query<employee>(query).SingleOrDefault();
        }

        public Employee Add(Employee employee)
        {
            var sqlQuery = "INSERT INTO tblEmployee (EmpName, EmpScore) VALUES(@EmpName, @EmpScore); " + "SELECT CAST(SCOPE_IDENTITY() as int)";
            var employeeId = this._db.Query<int>(sqlQuery, employee).Single();
            employee.EmpID = employeeId;
            return employee;
        }

        public Employee Update(Employee employee)
        {
            var sqlQuery =
            "UPDATE tblEmployee " +
            "SET EmpName = @EmpName, " +
            " EmpScore = @EmpScore " +
            "WHERE EmpID = @EmpID";
            this._db.Execute(sqlQuery, employee);
            return employee;
        }

        public void Remove(int id)
        {
            var sqlQuery =("Delete From tblEmployee Where EmpID = " + id + "");
            this._db.Execute(sqlQuery);
        }
    }
}
</int></employee></employee></employee>

8. Add Controller class EmployeeController.CS inside controller folder. In there you can create Template controller with read write actions. When you create views using the Employee controller you can use strongly Typed View Like below image.

Image 2

9. If you download the example you can see the full figure of controller and view. Here is the Controller class function for Edit.

C#
public ActionResult Edit(int id)
      {
          return View(_dashboard.Find(id));
      }

      // POST: /User/Edit/5
      // To protect from overposting attacks, please enable the specific properties you want to bind to, for
      // more details see http://go.microsoft.com/fwlink/?LinkId=317598.

      [HttpPost]
      public ActionResult Edit([Bind(Include = "EmpID,EmpName,EmpScore")] Employee employee, int id)
      {
          if (ModelState.IsValid)
          {
              _dashboard.Update(employee);
          }
          return View(employee);
      }

 

If you use above 9 steps you can simply create a simple MVC example with Dapper.NET. For get good idea about the sample you can download and see. 

Points of Interest

This is my first Sample code on Codeproject. I do not have good writing skills but I just wanted to give you a sample programme. Because most of the people finding samples for understand basic knowledge of new things. I used the same method and so I upload the sample here.
 

History

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot running Pin
Member 124282902-Dec-16 23:04
Member 124282902-Dec-16 23:04 
QuestionGood Post -- Hereis updates to work with Visual Studio 2013 and .net 4.5.1 Pin
Haneef Puttur3-Jun-15 20:22
Haneef Puttur3-Jun-15 20:22 
AnswerRe: Good Post -- Hereis updates to work with Visual Studio 2013 and .net 4.5.1 Pin
akky gohil8-Feb-24 23:05
akky gohil8-Feb-24 23:05 
QuestionDapper is just a data mapping tool , not an ORM Pin
John C Rayan19-May-15 23:42
professionalJohn C Rayan19-May-15 23:42 
AnswerRe: Dapper is just a data mapping tool , not an ORM Pin
alaa9jo17-Sep-15 2:38
alaa9jo17-Sep-15 2:38 
GeneralMy vote of 1 Pin
abecpark13-Aug-14 6:16
abecpark13-Aug-14 6:16 
GeneralRe: My vote of 1 Pin
PIEBALDconsult13-Aug-14 6:37
mvePIEBALDconsult13-Aug-14 6:37 
GeneralThoughts Pin
PIEBALDconsult13-Aug-14 5:19
mvePIEBALDconsult13-Aug-14 5:19 
GeneralRe: Thoughts Pin
Gihan Liyanage13-Aug-14 6:14
professionalGihan Liyanage13-Aug-14 6:14 
QuestionPlease parameterize queries Pin
patnsnaudy13-Aug-14 5:02
patnsnaudy13-Aug-14 5:02 
AnswerRe: Please parameterize queries Pin
Gihan Liyanage13-Aug-14 6:15
professionalGihan Liyanage13-Aug-14 6:15 
GeneralRemember Pin
Thelonious Monk13-Aug-14 2:07
Thelonious Monk13-Aug-14 2:07 
GeneralRe: Remember Pin
Gihan Liyanage13-Aug-14 6:16
professionalGihan Liyanage13-Aug-14 6:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.