Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
12 Aug 2014 1  
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.

 

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.

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

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. 
 

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.

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

  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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here