Stored Procedure Parameter Mapping with Dapper

In this article we will learn how to map stored procedure parameter with Dapper ORM .To learn more about Dapper please refer my following articles
 To map stored procedure with Dapper ORM  DynamicParameters class of Dapper is used, lets see how to map it
Suppose you have following Model class of parameters which values comes 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.


Watch Video  

Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me.

Read my other MVC articles
  




Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode