ORM之Dapper運用

1、前言

上一篇【分層架構設計】咱們已經有了架構的輪廓,如今咱們就在這個輪廓裏面造輪子。項目要想開始,確定先得肯定ORM框架,目前市面上的ORM框架有不少,對於.net人員來講很容易就想到以ADO.NET爲基礎所發展出來的ORM框架EntityFramework。不得不說EntityFramework是一個功能很強大的ORM框架,到如今最新的EF分別是EF6(.Net Framework)和EF Core(.Net Core)兩個版本。html

可是這裏我使用的另外一個叫Dapper的ORM框架,緣由是由於EF過重了,而Dapper是一個輕量級開源的ORM類,他是經過擴展IDbConnection提供一些有用的擴展方法去查詢您的數據庫,因此Ado.Net支持的數據庫,他均可以支持。在速度方面具備「King of Micro ORM」的頭銜,幾乎與使用原始的ADO.NET數據讀取器同樣快。第一次使用了他以後,就深深的喜歡上他了。git

github地址:https://github.com/StackExchange/Dappergithub

Dapper文檔:https://dapper-tutorial.net/dappersql

2、Dapper實現

2.一、Dapper的方法

從Dapper文檔中,咱們知道,Dapper支持一下的方法:數據庫

Execute:執行一次或屢次命令並返回受影響的行數,包括存儲過程
Query:執行查詢,返回類型爲t的數據(返回數據爲集合)
QueryFirst:執行查詢並映射第一個結果,若是沒有就爲null
QueryFirstOrDefault:行查詢並映射第一個結果,若是序列不包含任何元素,則能夠映射默認值
QuerySingle:行查詢並映射第一個結果,若是序列中沒有一個元素,則拋出異常
QuerySingleOrDefault:執行查詢並映射第一個結果,若是序列爲空則映射默認值;若是序列中有多個元素,則此方法拋出異常
QueryMultiple:在同一命令中執行多個查詢並映射結果
架構

Dapper還提供了上面方法相同功能的異步方法,同時每一個方法也支持多種形式的傳參。app

2.二、Dapper的使用

在前面的項目中,咱們在 「04-DataLayer」文件下面添加類庫「PFT.Snail.DataAccess」。PFT.Snail.DataAccess主要是 用來完成Dapper方法的使用。框架

在PFT.Snail.DataAccess項目下面建立文件「DapperSqlDB.cs」,代碼以下:異步

 public class DapperSqlDB
    {
        /// <summary>
        /// 鏈接字符串
        /// </summary>
        public string ConnectionString { get; set; }
        /// <summary>
        /// 數據庫鏈接時間
        /// </summary>
        private int _commondTimeout { get { return 1200; } }

        public DapperSqlDB()
        {
        }
        public DapperSqlDB(string connectionString)
        {
            ConnectionString = connectionString;
        }

        #region 查詢

        /// <summary>
        /// 查詢列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.Query<T>(sql, param, commandTimeout: _commondTimeout).ToList();
            }
        }

        /// <summary>
        /// 異步查詢列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> QueryAsync<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return await conn.QueryAsync<T>(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 查詢列表第一條數據
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public T QueryFirstOrDefault<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.QueryFirstOrDefault<T>(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 異步查詢列表第一條數據
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<T> QueryFirstOrDefaultAsync<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return await conn.QueryFirstOrDefaultAsync<T>(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 查詢選擇單個值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.ExecuteScalar<T>(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 異步查詢選擇單個值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<T> ExecuteScalarAsync<T>(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return await conn.ExecuteScalarAsync<T>(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /*調用方式
         * var multi=DBSqlHelper.QueryMultiple("",null);
         * var invoice = multi.Read<Invoice>().First();
         * var invoiceItems = multi.Read<InvoiceItem>().ToList();
         */
        /// <summary>
        /// 執行多個查詢並映射結果
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public GridReader QueryMultiple(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.QueryMultiple(sql, param, commandTimeout: _commondTimeout);
            }

        }

        /* 調用方式
         * await DBSqlHelper.QueryMultipleAsync(sql, para, async (reader) =>
         *  {
         *      rs.A= (await reader.ReadFirstAsync<SingleValue<decimal>>()).Value;
         *      rs.B= (await reader.ReadFirstAsync<SingleValue<decimal>>()).Value;
         *      ...
         *  });
         */
        /// <summary>
        /// 異步執行多個查詢並映射結果
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="readerCallback"></param>
        /// <returns></returns>
        public async Task QueryMultipleAsync(string sql, object param, Action<GridReader> readerCallback)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (var reader = await conn.QueryMultipleAsync(sql, param, commandTimeout: _commondTimeout))
                {
                    if (readerCallback != null)
                    {
                        readerCallback(reader);
                    }
                }

            }
        }

        #endregion

        #region 執行sql

        /// <summary>
        /// 執行sql語句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int Execute(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.Execute(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 異步執行sql語句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<int> ExecuteAsync(string sql, object param)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return await conn.ExecuteAsync(sql, param, commandTimeout: _commondTimeout);
            }
        }

        /// <summary>
        /// 執行sql語句(主要指存儲過程)
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int Execute(string sql, object param, CommandType type)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return conn.Execute(sql, param, commandTimeout: _commondTimeout, commandType: type);
            }
        }

        /// <summary>
        /// 異步執行sql語句(主要指存儲過程)
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<int> ExecuteAsync(string sql, object param, CommandType type)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                return await conn.ExecuteAsync(sql, param, commandTimeout: _commondTimeout, commandType: type);
            }
        }
        #endregion





    }

同時Nuget添加System.Data.SqlClient和Dapper的引用。async

上面已經實現了數據的增刪改查操做,可是再使用過程就會發現,沒有事務機制和分頁功能。

添加事務功能

在PFT.Snail.DataAccess中添加接口「ITransaction.cs」

public interface ITransaction
    {
        List<T> Query<T>(string sql, object param);
        T QueryFirstOrDefault<T>(string sql, object param);
        T ExecuteScalar<T>(string sql, object param);
        int Execute(string sql, object param);

    }

在「DapperSqlDB.cs」添加事務對象

        #region 事務方法

        /// <summary>
        /// 事務執行方法對象
        /// </summary>
        private class Transaction : IDisposable, ITransaction
        {
            private IDbConnection conn = null;
            private IDbTransaction tran = null;
            public Transaction(IDbConnection conn, IDbTransaction tran)
            {
                this.conn = conn;
                this.tran = tran;
            }


            List<T> ITransaction.Query<T>(string sql, object param)
            {
                return conn.Query<T>(sql, param, tran).ToList();
            }

            T ITransaction.QueryFirstOrDefault<T>(string sql, object param)
            {
                return conn.QueryFirstOrDefault<T>(sql, param, tran);
            }

            T ITransaction.ExecuteScalar<T>(string sql, object param)
            {
                return conn.ExecuteScalar<T>(sql, param, tran);
            }

            int ITransaction.Execute(string sql, object param)
            {
                return conn.Execute(sql, param, tran);
            }

            void IDisposable.Dispose()
            {
                if (this.tran != null)
                {
                    this.tran.Dispose();
                }

                if (this.conn != null)
                {
                    this.conn.Dispose();
                }
            }
        }

        #endregion

添加事務方法

/*調用方式
         * DBSqlHelper.ExecuteTransaction((trans) =>
         * {
         *     trans.Execute(sqlinsertct, selectedClass);
         *     trans.Execute(sqlinsertict, selectedClass);
         * });
         */
        /// <summary>
        /// 事務方法
        /// </summary>
        /// <param name="tranAction"></param>
        /// <param name="level"></param>
        /// <param name="newConnectionString"></param>
        public void ExecuteTransaction(Action<ITransaction> tranAction, IsolationLevel? level = null, string newConnectionString = null)
        {
            using (IDbConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                IDbTransaction tran = null;
                if (level == null)
                {
                    tran = conn.BeginTransaction();
                }
                else
                {
                    tran = conn.BeginTransaction(level.Value);
                }
                using (Transaction tranHelper = new Transaction(conn, tran))
                {
                    try
                    {
                        tranAction(tranHelper);
                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                        throw;
                    }
                }
            }
        }

添加分頁功能

在「PFT.Snail.Dto」中添加「Common」文件夾,下面在添加「PageResponse.cs」

/// <summary>
    /// 通用分頁返回
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PageResponse<T>
    {
        /// <summary>
        /// 總條數
        /// </summary>
        public long TotalCount { get; set; }

        /// <summary>
        /// 返回
        /// </summary>
        public List<T> Items { get; set; }

        /// <summary>
        /// 當前頁
        /// </summary>
        public long PageIndex { get; set; }

        /// <summary>
        /// 每頁條數
        /// </summary>
        public long PageSize { get; set; }

        /// <summary>
        /// 總頁數
        /// </summary>
        public long TotalPages { get; set; }

        /// <summary>
        /// 返回篩選集合
        /// </summary>
        public Dictionary<string, List<string>> ResultFilter = new Dictionary<string, List<string>>();

    }

在「DapperSqlDB.cs」添加分頁功能

        /// <summary>
        /// Sqlserver 分頁查詢(只支持Sqlserver2012以上數據庫)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public PageResponse<T> QueryPageSql<T>(PageRequest page, string sql, object param)
        {
            var pageResult = new PageResponse<T>();
            pageResult.PageIndex = page.PageIndex;

            var queryNumSql = new StringBuilder($"SELECT COUNT(1) FROM ({sql}) AS maptable");
            pageResult.TotalCount = ExecuteScalar<int>(queryNumSql.ToString(), param);
            if (pageResult.TotalCount == 0)
            {
                return pageResult;
            }

            var pageMinCount = (page.PageIndex - 1) * page.PageSize + 1;
            if (pageResult.TotalCount < pageMinCount)
            {
                page.PageIndex = (int)((pageResult.TotalCount - 1) / page.PageSize) + 1;
            }

            var querySql = new StringBuilder($@"SELECT maptable.* FROM ({sql}) AS maptable ");
            if (!string.IsNullOrWhiteSpace(page.SortBy))
            {
                querySql.AppendLine(page.GetOrderBySql());
            }
            querySql.AppendLine($" OFFSET {(page.PageIndex - 1) * page.PageSize} ROWS FETCH NEXT {page.PageSize} ROWS ONLY;");

            pageResult.Items = Query<T>(querySql.ToString(), param);
            return pageResult;
        }

分頁的代碼只支持SQl2012以上的版本,若是是一下的版本,能夠本身重構代碼。

到如今纔算把Dapper框架的運用方法所有實現了。

3、總結

雖然實現了Dapper框架的運用方法,可是在真實的項目中,運用這樣的方法或多或少有不少不便。同時在架構的設計來講,也不是太合理,由於Repository依賴DapperSqlDB的具體實現,須要抽象出接口。既然存在所說的問題,那爲何不直接寫出最終方法呢?這是由於必須弄清楚Dapper的運用,咱們纔可以對他進行定製化的優化。

相關文章
相關標籤/搜索