轻量型ORM框架Dapper的使用

在真实的项目开发中,可能有些人比较喜欢写SQL语句,但是对于EF这种ORM框架比较排斥,那么轻量型的Dapper就是一个不错的选择,即让你写sql语句了,有进行了关系对象映射。其实对于EF吧,我说下我个人的见解,EF是相对来说比较重的ORM框架,它是讲究通用性的框架,而非单纯的实现某种需求的框架,不得不否认的说,EF的开发效率要比用单纯的ADO.NET写sql语句的效率高的不是一点半点,可能很多人会说EF的性能低等等,针对这种问题有时候是需要折中的来讲,从另一个方面来讲,你用了ADO.NET写sql语句是性能好了,但是你得到的是弱类型的DataTable或者DataSet,常规在MVC的开发中,其实你难道不转换成集合或者单个对象吗?总不会拿着DataTable用吧,当你把弱类型的Datatable转换成List<T>的时候,一般来讲分两种转换,一种是利用反射,这其实也就成了关系对象映射了,跟ORM框架没什么区别了,第二种无非是循环赋值了,但是这种的开箱装箱的损耗也是很大的,最终你得到你想要的数据类型的时候其实折中算下来相比较EF直接得到,中间你又走了很多的弯路了,我在开发中一般EF打头阵,轻量的Dapper做辅助,因为有时候开发效率很重要,性能的问题我不会过多在SQL优化上下功夫,我一般会在中间缓存上做处理。下面是我简单的对Dapper的小包装,代码如下:

 

public class LiunianContext:IDisposable
    {
        private static readonly string _dbConnectionStr = ConfigurationManager.ConnectionStrings["XXXContext"].ConnectionString;


        private IDbConnection dbConnection;

        private IDbConnection DbConnection
        {
            get
            {
                if (_dbConnectionStr.IsNotNullOrEmpty())
                    dbConnection = new SqlConnection(_dbConnectionStr);
                else
                    throw new ArgumentNullException("dbConnectionStr");

                bool isClosed = dbConnection.State == ConnectionState.Closed;
                if (isClosed) dbConnection.Open();
                return dbConnection;
            }
        }

        /// <summary>
        /// 执行增删改操作(包括批量操作)
        /// </summary>
        /// <param name="sql">sql语句(有参数参数化)</param>
        /// <param name="param">参数化值</param>
        /// <returns></returns>
        public bool Execute(string sql, object param)
        {
            bool isSuccess = false;
            if (sql.IsNotNullOrEmpty())
            {
                try
                {
                    int result = DbConnection.Execute(sql, param);
                    isSuccess = result > 0 ? true : false;
                }
                catch
                {
                    isSuccess = false;
                }
            }
            return isSuccess;
        }

        /// <summary>
        /// 执行存储过程操作
        /// </summary>
        /// <param name="sql">存储过程名称</param>
        /// <param name="param">参数化值</param>
        /// <returns>返回存储过程是否执行成功</returns>
        public bool ExecuteStored(string storedName, object param)
        {
            bool isSuccess = false;
            if (storedName.IsNotNullOrEmpty())
            {
                try
                {
                    int result = DbConnection.Execute(storedName, param, commandType: CommandType.StoredProcedure);
                    isSuccess = result > 0 ? true : false;
                }
                catch
                {
                    isSuccess = false;
                }
            }
            return isSuccess;
        }

        /// <summary>
        /// 执行存储过程操作
        /// </summary>
        /// <param name="storedName">存储过程名称</param>
        /// <param name="param">存储过程参数</param>
        /// <returns>返回存储过程要返回的值</returns>
        public DynamicParameters ExecuteStored(string storedName, DynamicParameters param)
        {
            if (storedName.IsNotNullOrEmpty())
            {
                try
                {
                    DbConnection.Execute(storedName, param, commandType: CommandType.StoredProcedure);
                }
                catch { }
            }
            return param;
        }


        /// <summary>
        /// 查询操作
        /// </summary>
        /// <typeparam name="T">返回集合的类型</typeparam>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数化值</param>
        /// <returns></returns>
        public IEnumerable<T> Query<T>(string sql, object param)
        {
            IEnumerable<T> _list = default(IEnumerable<T>);
            if (!string.IsNullOrEmpty(sql))
            {
                try
                {
                    _list = DbConnection.Query<T>(sql, param);
                }
                catch { }
            }
            return _list;
        }

        /// <summary>
        /// 执行存储过程查询操作
        /// </summary>
        /// <typeparam name="T">返回集合的类型</typeparam>
        /// <param name="storedName">存储过程</param>
        /// <param name="param">参数化值</param>
        /// <returns></returns>
        public IEnumerable<T> QueryStored<T>(string storedName, object param)
        {
            IEnumerable<T> _list = default(IEnumerable<T>);
            if (!string.IsNullOrEmpty(storedName))
            {
                try
                {
                    _list = DbConnection.Query<T>(storedName,commandType: CommandType.StoredProcedure);
                }
                catch { }
            }
            return _list;
        }

        /// <summary>
        /// 查询操作返回默认第一条数据(如返回null则创建默认类型)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public T FirstOrDefault<T>(string sql, object param)
        {
            var model = default(T);
            if (!string.IsNullOrEmpty(sql))
            {
                try
                {
                    model = DbConnection.Query<T>(sql, param).FirstOrDefault();
                }
                catch { }
            }
            return model == null ? Activator.CreateInstance<T>() : model;
        }



        /// <summary>
        /// 查询一组SQL语句并返回值
        /// </summary>
        /// <typeparam name="T1">第一条语句返回集合类型</typeparam>
        /// <typeparam name="T2">第二条语句返回集合类型</typeparam>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数化值</param>
        /// <returns></returns>
        public Tuple<IEnumerable<T1>, IEnumerable<T2>> Query<T1, T2>(string sql, object param)
        {
            IEnumerable<T1> _item1 = null; IEnumerable<T2> _item2 = null;
            if (!string.IsNullOrEmpty(sql))
            {
                try
                {
                    using (var multi = DbConnection.QueryMultiple(sql, param))
                    {
                        _item1 = multi.Read<T1>();
                        _item2 = multi.Read<T2>();
                    }
                }
                catch { }
            }
            return Tuple.Create<IEnumerable<T1>, IEnumerable<T2>>(_item1, _item2);
        }

        /// <summary>
        /// 查询一组SQL语句并返回值
        /// </summary>
        /// <typeparam name="T1">第一条语句返回集合类型</typeparam>
        /// <typeparam name="T2">第二条语句返回集合类型</typeparam>
        /// <typeparam name="T3">第三条语句返回集合类型</typeparam>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数化值</param>
        /// <returns></returns>
        public Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>> Query<T1, T2, T3>(string sql, object param)
        {
            IEnumerable<T1> _item1 = null; IEnumerable<T2> _item2 = null; IEnumerable<T3> _item3 = null;
            if (!string.IsNullOrEmpty(sql))
            {
                try
                {
                    using (var multi = DbConnection.QueryMultiple(sql, param))
                    {
                        _item1 = multi.Read<T1>();
                        _item2 = multi.Read<T2>();
                        _item3 = multi.Read<T3>();
                    }
                }
                catch { }
            }
            return Tuple.Create<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>>(_item1, _item2, _item3);
        }



        public void Dispose()
        {
            if (dbConnection != null)
            {
                try
                {
                    bool isClosed = dbConnection.State == ConnectionState.Closed;
                    if (!isClosed) dbConnection.Close();
                    //dbConnection.Dispose();
                }
                catch { }
            }
        }
    }

调用示例如下:

 

public abstract class BaseProvide
    {
        public Lazy<LiunianContext> lazyContext;

        protected LiunianContextDb
        {
            get
            {
                return lazyContext.Value;
            }
        }

    }

   public class EmployeeProvide : BaseProvide
    {
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        public List<Employee> ListEmployeeByParam(int[] param)
        {
            string sql = "select * from Employee where ID in @Ids";
            return Db.Query<Employee>(sql, new { Ids = param }).ToList();
        }

        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <returns></returns>
        public List<Employee> ListEmployee()
        {
            string sql = "select * from Employee";
            return Db.Query<Employee>(sql,null).ToList();
        }

        /// <summary>
        /// 查询单个实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Employee loadEmployee(int Id)
        {
            string sql = "select * from Employee where ID= @Id";
            return Db.FirstOrDefault<Employee>(sql, new { Id = Id });
        }

        /// <summary>
        /// 插入操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool InsertEmployee(Employee model)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("insert into Employee values (@UpdateTime,@CreateTime,@State,@LoginName,@UserName,");
            sql.Append("@RoleId,@IsUse)");
            return Db.Execute(sql.ToString(), model);
        }

        /// <summary>
        /// 更新操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateEmployee(Employee model)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("update Employee set UpdateTime = @UpdateTime where  ID = @ID");
            return Db.Execute(sql.ToString(), model);
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool DeleteEmployeeById(int Id)
        {
            string sql = "delete from Employee where ID = @Id";
            return Db.Execute(sql.ToString(), new { Id = Id });
        }

        /// <summary>
        /// 执行多个语句返回多个结果
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Tuple<int,IEnumerable<Employee>> ListGroupEmployee()
        {
            string sql = "select Count(*) from Employee select * from Employee";
            Tuple<IEnumerable<int>, IEnumerable<Employee>> queryGroup = Db.Query<int, Employee>(sql, null);
            return Tuple.Create<int, IEnumerable<Employee>>(queryGroup.Item1.FirstOrDefault(),queryGroup.Item2);
        }


    }

除了没把事务加上之外其他的增删改查都有了,同时在传对象的时候Dapper也解决了sql注入的问题,在性能上也是比较好的ORM框架,需要的拿去!

posted @ 2015-11-09 22:15  流年莫逝  阅读(6327)  评论(13编辑  收藏  举报