Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 12 Aug 2014
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gihan Liyanage
Software Developer (Senior)
Sri Lanka Sri Lanka
Senior Engineer at Virtusa. C#, ASP.Net, Biztalk Server, MVC3, MVC4, WCF and SQL are my tags
Follow on   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberabecpark13-Aug-14 6:16 
GeneralRe: My vote of 1 PinmemberPIEBALDconsult13-Aug-14 6:37 
GeneralThoughts PinmemberPIEBALDconsult13-Aug-14 5:19 
GeneralRe: Thoughts PinmemberGihan Liyanage13-Aug-14 6:14 
QuestionPlease parameterize queries Pinmemberpatnsnaudy13-Aug-14 5:02 
AnswerRe: Please parameterize queries PinmemberGihan Liyanage13-Aug-14 6:15 
GeneralRemember PinmemberFernando Bracaroto13-Aug-14 2:07 
GeneralRe: Remember PinmemberGihan Liyanage13-Aug-14 6:16 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 12 Aug 2014
Article Copyright 2014 by Gihan Liyanage
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid