Friday, 30 March 2018

Implementing Dapper in asp.net

Step 1: Install Dapper nuget package using following command: 
  Install-Package Dapper

Step 2: Create new BaseService.cs class as following:
using Dapper;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace DapperDemo.Services
{
 public abstract class BaseService
    {
        protected readonly IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString);
        public BaseService()
        {
            if (_db.State == ConnectionState.Closed)
            {
                _db.Open();
            }
        }
        protected IList<T> Get<T>(string sql, object parameters, CommandType commandType = CommandType.Text)
        {
            return (IList<T>)_db.Query<T>(sql, parameters, commandType: commandType);
        }

        protected int Insert(string sql, object parameters, CommandType commanType = CommandType.Text)
        {
            sql = $"{sql}; Select Cast (Scope_Identity() as int)";
            return _db.Query<int>(sql, parameters, commandType: commanType).Single();
        }

        protected T GetSingle<T>(string sql, object parameters, CommandType commandType = CommandType.Text)
        {
            return _db.Query<T>(sql, parameters, commandType: commandType).SingleOrDefault();
        }

        protected void ExecuteSql(string sql, object parameters, CommandType commanType = CommandType.Text)
        {
            _db.Execute(sql, parameters, commandType: commanType);
        }
    }
}

Step 3: Now Create your service class and use the generic methods of BaseService.cs class as following:
public class TestService : BaseService
    {
        public void GetData()
        {
            String query = "select * from Courses";
            var result = Get<Course>(query, null);
        }

        public void GetDetails()
        {
            String query = "select * from Courses where id = @Id";
            var result = GetSingle<Course>(query, new { Id = 9 });
        }

        public void InsertCourse()
        {
            string sql = "insert into Courses(Name, Description) values (@Name, @Description)";

            var result = Insert(sql, new { Name = "Course3", Description = "Description" });
        }
    }

    public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

No comments:

Post a Comment