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  


Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode