Sunday, February 26, 2017

Dapper - Simple Example

1. Install Dapper from Nuget using this command..


Install-Package Dapper

2. configure connection string in your web.config..

add name="StudentDBContext" connectionString="Data Source=DELL-PC;Initial Catalog=Student;User ID=sa;Password=software123" providerName="System.Data.SqlClient"

3. Use this code for Dapper

public class DapperExecute
    {
        public string ConnectionString { get; set; }
        public DapperExecute()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString;
        }

        public ICollection Execute(string Statement, dynamic Parameters = null, CommandType commandtype = CommandType.StoredProcedure)
        {
            var result = (dynamic)null;
            try
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                    result = SqlMapper.Query(connection, Statement, Parameters, null, true, 0, commandtype);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

    }

4. Call using this Syntex....

 DapperExecute de = new DapperExecute();

 var student = de.Execute("usp_GetStudent", new
            {
                studentID = id
            }).FirstOrDefault();

Note: Use "FirstOrDefault()" only when you want to get only one record. If you want to get List, please remove this.

No comments:

Post a Comment