C# Dapper ORM操作各种数据帮助类 支持多种数据库 - 实用 - lbx

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lbx_15887055073/article/details/82083760

1、准备工作

在管理NuGet程序包中搜索 Dapper,安装Dapper ORM到要操作数据库的项目中。


2、基类

类代码如下:

public abstract class DataBase
    {
        /// <summary>
        /// 
        /// </summary>
        public abstract string ConnectionString { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="pName"></param>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>

        public DbParameter CreateParameter(DbCommand cmd, String pName, Object value, System.Data.DbType type)
        {
            var p = cmd.CreateParameter();
            p.ParameterName = pName;
            p.Value = (value == null ? DBNull.Value : value);
            p.DbType = type;
            return p;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public abstract DbCommand CreateCommand();

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public abstract DbConnection CreateConnection();

        /// <summary>
        /// 返回List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public List<T> Select<T>(string sql, Object paramObject = null)
        {
            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                var list = Dapper.SqlMapper.Query<T>(conn, sql, paramObject);
                return list.ToList<T>();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public List<dynamic> Select(string sql, Object paramObject = null)
        {
            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                var list = Dapper.SqlMapper.Query(conn, sql, paramObject);
                return list.ToList<dynamic>();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public dynamic Single(string sql, Object paramObject = null)
        {
            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                var list = Dapper.SqlMapper.QuerySingleOrDefault<dynamic>(conn, sql, paramObject);
                return list;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public T Single<T>(string sql, Object paramObject = null)
        {

            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                var list = Dapper.SqlMapper.QuerySingleOrDefault<T>(conn, sql, paramObject);
                return list;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return default(T);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 获取一行一列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string sql, Object paramObject = null)
        {

            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                T t = Dapper.SqlMapper.ExecuteScalar<T>(conn, sql, paramObject);
                return t;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return default(T);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 返回受影响行数
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public int Execute(string sql, Object paramObject = null)
        {
            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                int count = Dapper.SqlMapper.Execute(conn, sql, paramObject);
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 0;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// ExecuteNonQueryReturnId
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public int ExecuteNonQueryReturnId(string sql, Object paramObject = null)
        {
            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                int count = Convert.ToInt32(Dapper.SqlMapper.ExecuteScalar(conn, sql, paramObject));
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 0;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        /// <summary>
        /// 自行维护事务和连接
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public int ExecuteTran(DbConnection conn, string sql, Object paramObject, DbTransaction transaction)
        {
            int count = Dapper.SqlMapper.Execute(conn, sql, paramObject, transaction);
            return count;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public List<T> ExecuteStoredProcedure<T>(string sql, Object paramObject)
        {

            DbConnection conn = null;
            try
            {
                conn = CreateConnection();
                conn.Open();
                var list = Dapper.SqlMapper.Query<T>(conn, sql, paramObject, null, true, null, System.Data.CommandType.StoredProcedure);
                return list.ToList<T>();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
    }

3、重写其方法

代码如下:

public class SqlDataBase : DataBase
    {
        /// <summary>
        /// 
        /// </summary>
        public override string ConnectionString
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            }
        }

        /// <summary>
        /// 尽少用
        /// </summary>
        /// <returns></returns>
        public override DbCommand CreateCommand()
        {
            return new System.Data.SqlClient.SqlCommand();
        }

        /// <summary>
        /// 常用
        /// </summary>
        /// <returns></returns>
        public override DbConnection CreateConnection()
        {
            //Sql Server 数据库,更换数据库只需改这里即可
            DbConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = ConnectionString;
            return conn;
        }
    }

4、使用

使用时很简单
举列1(查询操作)代码如下:

var db = new SqlDataBase();
var sql = "select * from auth_user where id = @id";
var model = db.Single<auth_user>(sql, new { id = id });
//当key和变量一样时,new { id = id }可简写为new { id },不一样时不能简写

举列2(非查询操作)代码如下:

var db = new SqlDataBase();
//删除用户
var sql = $@"delete from auth_user where id = @id";
var i = db.Execute(sql, new { id });
展开阅读全文

没有更多推荐了,返回首页