How To Use SQL Stored Procedure with Dapper ORM

In this article, we will learn how to use the SQL stored procedures with dapper ORM by writing a few lines of code. Let's consider we have the following values that need to be inserted into the SQL database using a stored procedure with the help of dapper ORM.

  • Name
  • City
  • Address

Create the stored procedure to map the above parameters.

Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End 

Create the C# property class to map the above stored procedure parameters

    public class Employee

    {     
       [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; }

    }

Create the method to insert the values using the dapper.

       public void AddEmployee(Employee objEmp)

        {
            //Passing stored procedure using Dapper.NET
                connection();
                con.Execute("AddNewEmpDetails", objEmp, commandType: CommandType.StoredProcedure);
               
       }

 In the above method
  • Connection() is the method which contains the connection string .
  • Con is the SqlConnection class object.
  • AddNewEmpDetails is the stored procedure.
  • ObjEmp is the object of model class

Summary

I hope this article is useful for all readers. If you have any questions then type in comment box.

Related Article

Dapper Using SQL Stored Procedure

SQL stored procedures can be used with dapper ORM by writing the few lines of code. Let's consider we have following values needs to be inserted into the SQL database using stored procedure with the help of dapper ORM

  • Name
  • City
  • Address

Create the stored procedure to map the above parameters

Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End 

Create the C# property class to map the above stored procedure parameters

    public class Employee

    {     
       [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; }

    }

Create the method to insert the values using the dapper

       public void AddEmployee(Employee objEmp)

        {
            //Passing stored procedure using Dapper.NET
                connection();
                con.Execute("AddNewEmpDetails", objEmp, commandType: CommandType.StoredProcedure);
               
       }

In the above method
  • Connection() is the method which contains the connection string .
  • Con is the SqlConnection class object.
  • AddNewEmpDetails is the stored procedure.
  • ObjEmp is the object of model class
Summary

I hope this article is useful for all readers. If you have any questions then type in comment box.

Mapping Stored Procedure Parameter with Dapper ORM Using DynamicParameters

In this article we will learn how to map stored procedure parameter with Dapper ORM using DynamicParameters class of Dapper, Let's demonstrate it with step by step examples,
Suppose you have following model class which values assigned from UI

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; }
    }


Now consider following stored procedure we have

Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End  


Now following is the function which is used to map the stored procedure with Dapper

   public bool AddEmployee(EmpModel obj)
        {     
                DynamicParameters param = new DynamicParameters();
                param.Add("@Name", obj.Name);
param.Add("@City", obj.City);
param.Add("@Address",obj.Address);
                connection();
                con.Open();
                con.Execute("AddNewEmpDetails", param, commandType: CommandType.StoredProcedure);
                con.Close();
                return true;         
        }
 



In the above function
  •  Connection() is the method which contains the connection string .
  •  Con is the SqlConnection class object.
  • AddNewEmpDetails is the stored procedure.
  •  DynamicParameters is the Dapper class name to map parameter like as SqlCommand
  • EmpModel is  model class.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.Don't Forget To  


Inserting Data into Microsoft Azure SQL DataBase Using ASP.NET MVC

In my previous video tutorial we have learned how to create Azure (cloud) SQL Database and how to connect Azure SQL Database using SQL Server Management studio , Now In this article we will learn how to insert data into Microsoft Azure (cloud) SQL Database  using ASP.NET MVC . Let's learn step by step so beginners can also understand

Step 1: Create Azure (Cloud) SQL Database

First we need to create the Azure SQL Database from Microsoft Azure portal , If you are new to the Microsoft Azure and wanted to know how to create Azure SQL Database then watch my videos tutorials using following link
I hope you went through the steps described in video tutorials and created the database . Now login to your Azure portal, The created database will be listed like are as shown in the following image


The preceding Azure SQL Portal screenshot EDS is the Database and the Database server location  is Central India

Step 2 : 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:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. After clicking, the following window will appear:


Step 3: Create Model Class

Now let us create the model class named EmployeeModel.cs by right clicking on model folder and write the get set properties inside the EmployeeModel.cs class file as
EmployeeModel.cs
 
public class EmployeeModel  
  {  
      [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; }  
  
  }  

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 it will add the empty controller class
Step 5 : Create Table and Stored procedures.

Now before creating the view let us create the table name Employee in database according to our model fields to store the details



Now create the stored procedures to insert employee details into database , The code snippet will be look like as following
Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End  

Step 6 : Modify the EmployeeController.cs file.

Now open the EmployeeController.cs file and create the methods for inserting data into Azure SQL Database and for displaying view as

EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using UsingAzureDB.Models;
using System.Linq;
using System.Web.Mvc;
namespace UsingAzureDB
{

public class EmployeeController : Controller    
    {    
          
        private SqlConnection con;
        //To Handle connection related activities
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
            con = new SqlConnection(constr);

        }
          // GET: Employee/AddEmployee    
        public ActionResult AddEmployee()    
        {    
            return View();    
        }    
      
        // POST: Employee/AddEmployee    
        [HttpPost]    
        public ActionResult AddEmployee(EmployeeModel Emp)    
        {    
            try    
            {    
                if (ModelState.IsValid)    
                {    
                         
                    if (AddEmployee(Emp))    
                    {    
                        ViewBag.Message = "Employee details added successfully";    
                    }    
                }    
                  
                return View();    
            }    
            catch    
            {    
                return View();    
            }    
        }    
      
      //To Add Employee details
        public bool AddEmployee(EmployeeModel obj)
        {

            connection();
            SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@City", obj.City);
            com.Parameters.AddWithValue("@Address", obj.Address);        
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {

                return true;

            }
            else
            {

                return false;
            }
        }
              
    } 
}       

Step 7: Create strongly typed view.


To create the 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 EmployeeModel.cs , It will create the view named AddEmployee.cshtml

 AddEmployee.cshtml


@model UsingAzureDB.Models.EmployeeModel  
@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>  
  
}  
  

Step 8 - Run the Application
 
After running the application enter the appropriate values into the text boxes and click on save button it will insert the records into the Azure SQL  database as shown in the following image


 Now lets open the Azure SQL database using SQL server management studio , It will shows the inserted records are as follows



From the preceding examples we have learned how to insert data into Azure SQL database using ASP.NET MVC.

Note:
  • Configure the Database connection string in the web.config file depending on your Azure SQL Database server credentials.
  • To Use Azure SQL Database you need Microsoft Azure Subscription
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

Don't Forget To 

Return Value From Dapper with Stored Procedure

Sometimes in an  we need to give user acknowledgment of their raised request or transaction reference number instantly from database which is generated against that user request. So for this purpose we need to take return value from stored procedure which is either string or integer or anything as per application requirement. Now in this article we will learn how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with one scenario-based sample MVC application.
Scenario
 Let's consider ABC housing society provides different services to their flat owners.  Since ABC housing society is very big it's difficult to manage complaints manually of their flat customers, so they decided to build the sample application which covers the following scenario .
  • User can raise the complaint type and short description using Text boxes .
  • The unique ComplaintId need to be generated instantly after raising the complaint to track status.
  • The ComplaintId should be the combination of first four characters of complaint type text and Database auto generated number.
So based on preceding scenario let's start building application step by step so beginners can also understand .
Step 1: Create an MVC Application.
 Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "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:
  1. 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.
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:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "dapper".
  3. Select Dapper as shown into the image .
  4. 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 such as:

If wants to learn how to install correct Dapper library , watch my video tutorial using following link,
I hope you have followed the same steps and installed dapper library.
Step 3: Create Model Class.
Now let's create the model class named ComplaintModel.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.
ComplaintModel.cs class code snippet: 

public class ComplaintModel  
    {   [Display(Name = "Complaint Type")]  
        [Required]  
        public string ComplaintType { get; set; }  
        [Display(Name = "Complaint Description")]  
        [Required]  
        public string ComplaintDesc { get; set; }  
    }
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 window. specify the Controller name as Complaint with suffix Controller:
Note:

The controller name must be having suffix as 'Controller' after specifying the name of controller.
Step 5 : Create Table and Stored procedure.

Now before creating the views let us create the table name ComplaintDetails in database according to store the complaint details:
I hope you have created the same table structure as shown above. Now create the stored procedures to get the return value  as in the following code snippet:
Create PROCEDURE AddComplaint  
(  
@ComplaintType varchar(100),  
@ComplaintDesc varchar(150),  
@ComplaintId varchar(20)=null out  
)  
AS  
BEGIN  
SET NOCOUNT ON;  
  
Declare @ComplaintRef varchar(30)  
--Getting unquie Id  
select @ComplaintRef=isnull(max(Id),0)+1 from ComplaintDetails  
--Generating the unique reference number and seeting to output parameter  
Set @ComplaintId=Upper(LEFT(@ComplaintType,4))+convert(Varchar,@ComplaintRef)  
  
INSERT INTO [dbo].[ComplaintDetails]  
           (  
            [ComplaintId]  
           ,[ComplaintType]  
           ,[ComplaintDesc]  
           )  
     VALUES  
           (  
          @ComplaintId,  
          @ComplaintType,  
          @ComplaintDesc  
           )  
END  
Run the above script in sql it will generates the stored procedure to get the return value .
Step 6: Create Repository class.
Now create Repository folder and Add ComplaintRepo.cs class for database related operations, Now create method in ComplaintRepo.cs to get the output parameter value from stored procedure as in the following code snippet:
public class ComplaintRepo  
  {  
      SqlConnection con;  
      //To Handle connection related activities  
      private void connection()  
      {  
          string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
          con = new SqlConnection(constr);  
      }  
      //To Add Complaint details  
      public string AddComplaint(ComplaintModel Obj)  
      {  
          DynamicParameters ObjParm = new DynamicParameters();  
          ObjParm.Add("@ComplaintType", Obj.ComplaintType);  
          ObjParm.Add("@ComplaintDesc", Obj.ComplaintDesc);  
          ObjParm.Add("@ComplaintId", dbType:DbType.String,direction:ParameterDirection.Output,size:5215585);  
          connection();  
          con.Open();  
          con.Execute("AddComplaint",ObjParm,commandType:CommandType.StoredProcedure);  
          //Getting the out parameter value of stored procedure  
          var ComplaintId = ObjParm.Get<string>("@ComplaintId");  
          con.Close();  
          return ComplaintId;  
  
      }  
  }  
Note
  1. 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.
Step 7: Create Method into the ComplaintController.cs file.

Now open the ComplaintController.cs and create the following action methods:
public class ComplaintController : Controller  
   {  
       // GET: complaint  
       public ActionResult AddComplaint()  
       {  
           return View();  
       }  
       [HttpPost]  
       public ActionResult AddComplaint(ComplaintModel ObjComp)  
       {  
           try  
           {  
               ComplaintRepo Obj = new ComplaintRepo();  
               //Getting complaintId and assigning   
               //to ViewBag with custom message to show user  
               ViewBag.ComplaintId = "Complaint raised successfully, Your complaintId is " + Obj.AddComplaint(ObjComp);  
           }  
           catch (Exception)  
           {  
               //Assigning custom message to ViewBag to show users, If any error occures.  
               ViewBag.ComplaintId="Error while raising complaint, Please check details";  
           }  
           return View();  
       }  
   }  
Step 8 : Creating strongly typed view named AddComplaint using ComplaintModel class .
Right click on View folder of created application and choose add view , select ComplaintModel class and create scaffolding template to create view to raise the user complaints as
 Click on Add button then it will create the view named AddComplaint, Now open the AddComplaint.cshtml view , Then following default code you will see which is generated by MVC scaffolding template as,
AddComplaint.cshtml  



@model GetReturnValueUsingDapperInMVC.Models.ComplaintModel   
@{  
    ViewBag.Title = "www.compilemode.com";  
}   
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">      
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.ComplaintType, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ComplaintType, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ComplaintType, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.ComplaintDesc, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ComplaintDesc, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ComplaintDesc, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Add Complaint" class="btn btn-primary" />  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
                @ViewBag.ComplaintId  
            </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> 
After adding model, view , controller and Repository folder our final solution explorer will be look like as follows,

Now we have done all coding to upload files .
Step 9 : Now run the application.
After running the application initial screen will be look like as follows,
Now click on Add Complaint button without entering the details then the following error message shows which we have defined in model class as
 Now enter the proper details as,

I hope from all the preceding example we have learned how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with real time scenario based sample MVC application.
Note:

  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • Configure the database connection in the web.config file depending on your database server location.
  • You can use  DropDownList for complaint types which might be come from master table.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.
Read more articles on ASP.NET MVC:

My Upcoming Speaking : Building Distributed Architecture using ASP.NET Web API with Azure SQL Database

Speaking at C# Corner Pune Chapter event on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database , If you wants to learn how to build and decide architecture for application  then join my interactive session on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database.

Agenda

 Date : 19-11-2016


Building Distributed Architecture using ASP.NET Web API with Azure SQL Database
  • User Story
  • What is a Distributed Architecture?
  • Tier Vs Layer Architecture
  • WCF REST Vs Web API REST?
  • Designing & understanding Distributed architecture diagram
  • Building REST Service Layer
  • Building Business Logic Layer
  • Building Entity Layer
  • Building Data Access Layer with Dapper ORM
  • Creating Azure SQL database
  • Connecting Data Access Layer with Azure SQL database
  • Building Client Layer with ASP.NET MVC
  • Hosting layers on different machines
  • Consuming Web API REST Services in ASP.NET MVC using HttpClient
  • Consuming Web API REST Services in Windows Phone and Windows Application
  • Q & A


        Where:

        Fujitsu Consulting India
        A-15, IT Tower, M I D C Technology Park, 
        Talwade , Pimpri-Chinchwad - 412114
        Pune Maharashtra INDIA


        Price: Free of cost

        Requirement: Optional to bring your laptop and internet card.

        Date : 19-11-2016
        Time :04:00 PM - 05:30 PM

                                      Register Now

        Don't forget to connect with me

        www.CodeNirvana.in

        Protected by Copyscape
        Copyright © Compilemode