Dapper的封装、二次封装、官方扩展包封装,以及ADO.NET原生封装

前几天偶然看到了dapper,由于以前没有用过,只用过ef core,稍微看了一下,然后写了一些简单的可复用的封装。

Dapper的用法比较接近ADO.NET所以性能也是比较快。所以我们先来看看使用ADO.NET的时候我们怎么实现代码复用的封装。

一、ADO.NET的封装案例

利用反射对ADO.NET进行封装,看代码:
DBHelper.cs:这边用的是mysql,如果要用sqlserver将MySqlConnection换成SqlConnection即可。
这个写的比较简单,如果有复杂的sql可能就支持不了了。读取配置文件的代码需要用到两个包:
image

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using MySqlConnector;

namespace DB.Model
{
    public class DBHelper
    {
        private static IConfiguration Configuration { get; set; }
        private static readonly string ConnStr = null;
        private static MySqlConnection conn;
        static DBHelper()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }).Build();
            ConnStr = Configuration.GetConnectionString("MySql");
        }
        public static void Init()
        {
            if (conn==null)
            {
                conn = new MySqlConnection(ConnStr);
                conn.Open();
            }
            else if (conn.State== ConnectionState.Closed)
            {
                conn.Open();
            }
            else if(conn.State==ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }
        /// <summary>
        /// 查全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetDataAll<T>()
        {
            Init();
            Type type = typeof(T);
            //用type.Name代替表名
            string sql = $"select * from {type.Name}";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            List<T> Data = new List<T>();
            MySqlDataReader reader= cmd.ExecuteReader();
            while (reader.Read())
            {
                object obj = Activator.CreateInstance(type);
                foreach (PropertyInfo property in type.GetProperties())
                {
                    property.SetValue(obj,reader[property.Name]);
                }
                Data.Add((T)obj);
            }
            reader.Close();
            conn.Close();
            return Data;
        }
        /// <summary>
        /// 按id查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T GetDataById<T>(int id)
        {
            Init();
            Type type = typeof(T);
            string sql = $"select * from {type.Name} where id={id}";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            MySqlDataReader reader = cmd.ExecuteReader();
            object obj = Activator.CreateInstance(type);
            while (reader.Read())
            {
                foreach (PropertyInfo property in type.GetProperties())
                {
                    property.SetValue(obj,reader[property.Name]);
                }
            }
            reader.Close();
            conn.Close();
            return (T) obj;
        }
        /// <summary>
        /// 单条添加数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static int Add<T>(T t)
        {
            Init();
            Type type = t.GetType();
            Func<PropertyInfo, object> f = (x) =>
            {
                if (x.GetValue(t).GetType().Equals(typeof(string)))
                {
                    return $"'{x.GetValue(t)}'";
                }
                else
                {
                    return x.GetValue(t);
                }
            };
            string sql = $"insert into {type.Name} " +
                         $"({string.Join(",", type.GetProperties().Select(n => $"`{n.Name}`"))}) " +
                         $"values({string.Join(",", type.GetProperties().Select(n => $"{f(n)}"))})";
            MySqlCommand cmd = new MySqlCommand(sql,conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result;
        }
    }
}

二、Dapper原生封装

dapper框架是给IDBConnection写了一些扩展方法,底层还是反射实现对象的关系映射。我们使用的时候只需要会用泛型即可。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Model
{
    public class DapperHelper
    {
        static DapperHelper()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载   
            _dbConnection = new SqlConnection();
            _dbConnection.ConnectionString = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build().GetConnectionString("Default");
        }

        private static readonly IDbConnection _dbConnection;

        #region Query
        public async Task<T> QueryFirstOrDefaultAsync<T>(string sql, object param = null, IDbTransaction transaction = null,
            int? commandTimeout = null, CommandType? commandType = null)
        {
            return await _dbConnection.QueryFirstOrDefaultAsync<T>(sql, param, transaction, commandTimeout, commandType);
        }
        public T QueryFirstOrDefault<T>(string sql, object param = null, IDbTransaction transaction = null,
            int? commandTimeout = null, CommandType? commandType = null)
        {
            return _dbConnection.QueryFirstOrDefault<T>(sql, param, transaction, commandTimeout, commandType);
        }
        public async Task<List<T>> QueryAsync<T>(string sql, object param = null, IDbTransaction transaction = null,
            int? commandTimeout = null, CommandType? commandType = null)
        {
            return (await _dbConnection.QueryAsync<T>(sql, param, transaction, commandTimeout, commandType)).ToList();
        }
        public List<T> Query<T>(string sql, object param = null, IDbTransaction transaction = null,
            bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
        {
            return _dbConnection.Query<T>(sql, param, transaction, buffered, commandTimeout, commandType).ToList();
        }
        #endregion

        #region Excute
        public Task<int> ExecuteAsync(string sql, object param = null, IDbTransaction transaction = null,
            int? commandTimeout = null, CommandType? commandType = null)
        {
            return _dbConnection.ExecuteAsync(sql, param, transaction, commandTimeout, commandType);
        }
        public int Execute(string sql, object param = null, IDbTransaction transaction = null,
            int? commandTimeout = null, CommandType? commandType = null)
        {
            return _dbConnection.Execute(sql, param, transaction, commandTimeout, commandType);
        }


        #endregion
    }
}

使用:

using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace dapperDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            #region 原生dapper封装
            DapperHelper dapper = new DapperHelper();

            #region 查询集合

            Console.WriteLine("-----------------查询集合-------------------");
            var students = await dapper.QueryAsync<Student>("select * from Student");
            Console.WriteLine(JsonConvert.SerializeObject(students));
            #endregion

            #region 单个查询
            Console.WriteLine("-----------------单个查询-------------------");
            string sql = "select * from student where StudentName=@StudentName";
            var stu = await dapper.QueryFirstOrDefaultAsync<Student>(sql, new { StudentName = "小红帽" });
            Console.WriteLine(JsonConvert.SerializeObject(stu));
            #endregion

            #region 新增
            Console.WriteLine("-----------------新增-------------------");
            Student student = new Student()
            {
                Id = Guid.NewGuid(),
                StudentName = "小红帽",
                Sex = SexType.Male,
                CreateTime = DateTime.Now,
                IsDelete = false,
                Birthday = DateTime.Now
            };
            string excuteSql = "insert into student(id,studentname,sex,createtime,isdelete,birthday)" +
                               " values(@Id,@StudentName,@Sex,@CreateTime,@IsDelete,@Birthday)";
            var result = await dapper.ExecuteAsync(excuteSql, student);
            Console.WriteLine(result);
            #endregion

            #region 删除
            Console.WriteLine("-----------------删除-------------------");
            string deleteSql = "delete from student where studentname=@studentName";
            var result = await dapper.ExecuteAsync(deleteSql, new {studentName = "小红帽"});
            Console.WriteLine($"结果:{result}");
            #endregion

            #region 修改
            Console.WriteLine("-----------------修改-------------------");
            string updateSql = "update student set studentname=@NewStudentName where studentName=@OldStudentName";
            var result = await dapper.ExecuteAsync(updateSql, new {NewStudentName = "杜甫", OldStudentName = "李白" });
            Console.WriteLine($"结果:{result}");
            #endregion

            #endregion 原生dapper封装

        }
    }
}

三、Dapper的二次封装(基于上一个)

利用反射对Dapper进行二次封装:DapperSuperHelper.cs,通过继承继承dapper的封装,我们可以即可用使用原始封装又可以使用通用的对单表的增删改查。

该封装可以实现对单个表的增删改查,以及分页查询,修改、删除、查询都是基于id查询,id支持任意类型。

注意:修改的时候建议先查出数据再执行修改,因为目前封装的代码无法实现只更改某个字段,暂时是全部更改,必填项必须有值。非必填,不传值,即为null。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Model
{
    public class DapperSuperHelper<T>:DapperHelper
    {
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsync()
        {
            var sql = $"select * from {typeof(T).Name}";
            return await QueryAsync<T>(sql);
        }
        public List<T> GetAll()
        {
            var sql = $"select * from {typeof(T).Name}";
            return Query<T>(sql);
        }
        /// <summary>
        /// 按id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Get(object id)
        {
            var sql = $"select * from {typeof(T).Name} where id=@Id";
            return QueryFirstOrDefault<T>(sql, new {Id = id});
        }

        public async Task<T> GetAsync(object id)
        {
            var sql = $"select * from {typeof(T).Name} where id=@Id";
            return await QueryFirstOrDefaultAsync<T>(sql, new { Id = id });
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(T t)
        {
            Type type = t.GetType();
            var sql = $"insert into {type.Name}" +
                      $"({string.Join(",",type.GetProperties().Select(n=>n.Name))})"+
                      $" values({string.Join(",",type.GetProperties().Select(n=>$"@{n.Name}"))})";
            return await ExecuteAsync(sql,t);
        }
        public int Insert(T t)
        {
            Type type = t.GetType();
            var sql = $"insert into {type.Name}" +
                      $"({string.Join(",", type.GetProperties().Select(n => n.Name))})" +
                      $" values({string.Join(",", type.GetProperties().Select(n => $"@{n.Name}"))})";
            return Execute(sql, t);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T t)
        {
            Type type = t.GetType();
            var sql = $"update {type.Name} set " +
                      $"{string.Join(",", type.GetProperties().Select(n => $"{n.Name}=@{n.Name}"))} " +
                      $"where id=@Id";
            return await ExecuteAsync(sql,t);
        }
        public int Update(T t)
        {
            Type type = t.GetType();
            var sql = $"update {type.Name} set " +
                      $"{string.Join(",", type.GetProperties().Select(n => $"{n.Name}=@{n.Name}"))} " +
                      $"where id=@Id";
            return Execute(sql, t);
        }
        /// <summary>
        /// 按id删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(object id)
        {
            var sql = $"delete from {typeof(T).Name} where id=@Id";
            return await ExecuteAsync(sql, new { Id = id }) > 0;
        }

        public bool Delete(object id)
        {
            var sql = $"delete from {typeof(T).Name} where id=@Id";
            return Execute(sql, new { Id = id }) > 0;
        }
        /// <summary>
        /// 删除全部
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DeleteAllAsync()
        {
            var sql = $"delete from {typeof(T).Name}";
            return await ExecuteAsync(sql) > 0;
        }

        public bool DeleteAll()
        {
            var sql = $"delete from {typeof(T).Name}";
            return Execute(sql) > 0;
        }
        /// <summary>
        /// 单表分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<List<T>> GetPagedAsync(int pageIndex,int pageSize)
        {
            var skipRow = (pageIndex - 1) * pageSize;
            var sql = $"select * from {typeof(T).Name} order by Id " +
                      $"offset @skipRow rows fetch next @PageSize rows only";
            return await QueryAsync<T>(sql, new {skipRow, pageSize});
        }
        /// <summary>
        /// 单表分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<T> GetPaged(int pageIndex, int pageSize)
        {
            var skipRow = (pageIndex - 1) * pageSize;
            var sql = $"select * from {typeof(T).Name} order by Id " +
                      $"offset @skipRow rows fetch next @PageSize rows only";
            return Query<T>(sql, new { skipRow, pageSize });
        }
    }
}

使用:

using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace dapperDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            #region dapper二次封装
            DapperSuperHelper<Student> superDapper = new DapperSuperHelper<Student>();
            //查询所有
            List<Student> students = await superDapper.GetAllAsync();
            Console.WriteLine(JsonConvert.SerializeObject(students));

            //按id查询
            var id = Guid.Parse("b2847592-90d6-40a4-b3b0-c1ebf514e258");
            var stu = await superDapper.GetAsync(id);
            Console.WriteLine(JsonConvert.SerializeObject(stu));

            //新增
            Student entity = new Student()
            {
                Id = Guid.NewGuid(),
                Birthday = DateTime.Now,
                CreateTime = DateTime.Now,
                Email = "[email protected]",
                IsDelete = false,
                Sex = SexType.Female,
                StudentName = "夏花"
            };
            var result = await superDapper.InsertAsync(entity);
            Console.WriteLine($"新增结果,受影响的行数:{result}");

            //修改
            entity.StudentName = "小燕子";
            var updateResult = await superDapper.UpdateAsync(entity);
            Console.WriteLine($"修改结果,受影响的行数:{updateResult}");

            //删除
            var did = Guid.Parse("b2847592-90d6-40a4-b3b0-c1ebf514e258");
            var deleteResult = await superDapper.DeleteAsync(did);
            Console.WriteLine($"删除结果:{deleteResult}");

            //分页查询
            var pagedResult = await superDapper.GetPagedAsync(2, 2);
            Console.WriteLine(JsonConvert.SerializeObject(pagedResult));
            #endregion

        }
    }
}

四、Dapper官方提供的扩展包

image

原理和我通过反射进行的二次封装差不多,但是肯定比我写的更安全和规范、更复杂,不过官方的id我看了一下,好像只支持int类型。

可以看到我上面的二次封装和官方的封装其实差不多的功能,不过我还多了一个分页,嘿嘿。

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
using Microsoft.Extensions.Configuration;

namespace Model
{
    public class DapperExtHelper<T> where T:class
    {
        static DapperExtHelper()
        {
            _dbConnection = new SqlConnection();
            _dbConnection.ConnectionString = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build().GetConnectionString("Default");
        }

        private static readonly IDbConnection _dbConnection;

        public List<T> GetAll()
        {
            return _dbConnection.GetAll<T>().ToList();
        }
        public async Task<List<T>> GetAllAsync()
        {
            return (await _dbConnection.GetAllAsync<T>()).ToList();
        }
        public T Get(int id)
        {
            return _dbConnection.Get<T>(id);
        }

        public bool Update(T entity)
        {
            return _dbConnection.Update(entity);
        }

        public async Task<bool> UpdateAsync(T entity)
        {
            return await _dbConnection.UpdateAsync(entity);
        }
        public long Insert(T entity)
        {
            return _dbConnection.Insert(entity);
        }
        public async Task<long> InsertAsync(T entity)
        {
            return await _dbConnection.InsertAsync(entity);
        }

        public bool Delete(T entity)
        {
            return _dbConnection.Delete(entity);
        }
        public async Task<bool> DeleteAsync(T entity)
        {
            return await _dbConnection.DeleteAsync(entity);
        }
        public bool DeleteAll()
        {
            return _dbConnection.DeleteAll<T>();
        }
        public async Task<bool> DeleteAllAsync()
        {
            return await _dbConnection.DeleteAllAsync<T>();
        }
    }
}

使用:

using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace dapperDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {

            #region dapper官方自带的扩展包
            //查全部,官方默认会以类名后面加个s,我们最好指定[Table("Student")]
            DapperExtHelper<Student> dapperExtHelper = new DapperExtHelper<Student>();
            var students = dapperExtHelper.GetAll();
            Console.WriteLine(JsonConvert.SerializeObject(students));
            //id查询 只支持id为int
            //var stu = dapperExtHelper.Get(1);
            //删除全部
            //dapperExtHelper.DeleteAll();
            //删除
            var delEntity = new Student()
            {
                Id = Guid.Parse("c066dfce-d7cd-46b5-9fa3-d0aa4b165dde")
            };
            //dapperExtHelper.Delete(delEntity);
            //修改 全部字段修改,需要传递必填的参数,否则报错,未传的参数修改为空,因此最好是先查出当实体,再修改单独字段
            var updEntity = new Student()
            {
                Id = Guid.Parse("b2847592-90d6-40a4-b3b0-c1ebf514e257"),
                StudentName = "李白222",
                CreateTime = DateTime.Now,
                Birthday = DateTime.Now
            };
            dapperExtHelper.Update(updEntity);
            //新增 这居然报错,id不能传null,就离谱,估计和类型有关
            Student InsertEntity = new Student()
            {
                Id = Guid.NewGuid(),
                Birthday = DateTime.Now,
                CreateTime = DateTime.Now,
                Email = "[email protected]",
                IsDelete = false,
                Sex = SexType.Female,
                StudentName = "夏花"
            };
            dapperExtHelper.Insert(InsertEntity);



            #endregion
        }
    }
}

以上就是我对dapper的简单的封装。大家也可以自行封装。

Tags: