Bind Generic List From Stored Procedure Using Dapper

In this article we will learn how to Bind generic list from stored procedure using Dapper ORM. To learn more about dapper ORM please read my following articles
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 using we are getting the records from database

CREATE Procedure [dbo].[GetEmployees]  
as  
begin  
select Id as Empid,Name,City,Address from Employee
End 

Now following is the function which is used to bind generic list from stored procedure using Dapper


public List<EmpModel> GetAllEmployees()
        {
        try
            {
                connection();
                con.Open();
                IList<EmpModel> EmpList = SqlMapper.Query<EmpModel>(
                                  con, "GetEmployees").ToList();
                con.Close();
        return EmpList.ToList();
            }
        catch (Exception)
            {
        throw;
            }
        }

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

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode