码迷,mamicode.com
首页 > 其他好文 > 详细

ServiceStack.OrmLite简单扩展

时间:2016-07-15 23:55:52      阅读:2250      评论:0      收藏:0      [点我收藏+]

标签:

ServiceStack.OrmLite框架将所有的方法都扩展到了一个IDbConnection对象上,使用起来不是 很方便,在此对该框架做一个简单的封装。

OrmLiteExecFilterExt类

技术分享
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace ServiceStack.OrmLite.Extension
{
    public class OrmLiteExecFilterExt : OrmLiteExecFilter
    {
        /// <summary>
        /// 记录最后一次执行的完整SQL语句
        /// </summary>
        /// <param name="dbCmd"></param>
        /// <param name="dbConn"></param>
        /// <remarks>框架默认通过IDbConnection访问最后一次执行的SQL语句中不包含参数信息</remarks>
        public override void DisposeCommand(IDbCommand dbCmd, IDbConnection dbConn)
        {
            if (dbCmd == null) return;
            StringBuilder sql = new StringBuilder();
            sql.Append("SQL: ").Append(dbCmd.CommandText);
            if (dbCmd.Parameters.Count > 0)
            {
                sql.AppendLine()
                  .Append("PARAMS: ");
                for (int i = 0; i < dbCmd.Parameters.Count; i++)
                {
                    var p = (IDataParameter)dbCmd.Parameters[i];
                    if (i > 0)
                        sql.Append(", ");
                    sql.AppendFormat("{0}={1}", p.ParameterName, p.Value);
                }
            }
            dbConn.SetLastCommandText(sql.ToString());
            dbCmd.Dispose();
        }
    }
}
View Code

IDBEntity接口:暂时只用来标识一个对象是数据库实体对象

技术分享
using System;
namespace ServiceStack.Orm.Extension.Interface
{
    public interface IDBEntity
    {
    }
}
View Code

IOrmClient接口:定义了一系列数据库底层操作

技术分享
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ServiceStack.Orm.Extension.Interface
{
    public interface IOrmClient
    {
        /// <summary>
        ///     执行一个数据库操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        T Execute<T>(Func<IDbConnection, T> action);
        /// <summary>
        ///     执行一个数据库操作
        /// </summary>
        /// <param name="action"></param>
        void Execute(Action<IDbConnection> action);
        /// <summary>
        ///   获取一个表的SqlExpression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        SqlExpression<T> From<T>() where T : IDBEntity, new();
        /// <summary>
        ///     新增方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="selectIdentity">主键为自增长列时,返回新增数据的主键值</param>
        /// <returns></returns>
        long Insert<T>(T entity, bool selectIdentity = false) where T : IDBEntity, new();
        /// <summary>
        ///     批量新增方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        void InsertAll<T>(IEnumerable<T> entities) where T : IDBEntity, new();
        /// <summary>
        ///     更新方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        long Update<T>(T entity) where T : IDBEntity, new();
        /// <summary>
        ///     更新方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        long Update<T>(T entity, Expression<Func<T, bool>> where) where T : IDBEntity, new();
        /// <summary>
        ///     更新方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="onlyFields"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        /// <remarks>更新一行数据的部分字段</remarks>
        long Update<T>(T entity, Expression<Func<T, object>> onlyFields = null, Expression<Func<T, bool>> where = null) where T : IDBEntity, new();
        /// <summary>
        ///     批量更新方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        void UpdateAll<T>(IEnumerable<T> entities) where T : IDBEntity, new();
        /// <summary>
        ///     删除方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        long Delete<T>(SqlExpression<T> where) where T : IDBEntity, new();
        /// <summary>
        ///     删除方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        long Delete<T>(Expression<Func<T, bool>> where) where T : IDBEntity, new();
        /// <summary>
        ///     查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        List<T> Select<T>(SqlExpression<T> expression) where T : IDBEntity, new();
        /// <summary>
        ///     查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        List<T> Select<T>(Expression<Func<T, bool>> predicate) where T : IDBEntity, new();
        /// <summary>
        ///     查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        IEnumerable<T> SelectLazy<T>(SqlExpression<T> expression) where T : IDBEntity, new();
        /// <summary>
        ///     统计方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        long Count<T>(SqlExpression<T> expression) where T : IDBEntity, new();
        /// <summary>
        ///     查询指定条件的数据是否存在
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        bool Exist<T>(SqlExpression<T> expression) where T : IDBEntity, new();
        /// <summary>
        ///     读取满足条件的第一行第一列的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        T Scalar<T>(SqlExpression<T> expression) where T : IDBEntity, new();
        /// <summary>
        ///     执行一个语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        int ExecuteSql(string sql, object dbParams = null);
        /// <summary>
        ///     在事物中执行一个批操作
        /// </summary>
        /// <param name="actions"></param>
        /// <returns>事物是否执行成功</returns>
        bool InvokeTransaction(IEnumerable<Func<long>> actions);
        /// <summary>
        ///     在事物中执行一个批操作
        /// </summary>
        /// <param name="action"></param>
        /// <returns>事物是否成功</returns>
        bool InvokeTransaction(Func<bool> action);
        /// <summary>
        ///     在事物中执行一个批操作
        /// </summary>
        /// <param name="action"></param>
        /// <returns>事物是否成功</returns>
        bool InvokeTransaction(Func<bool> action, IsolationLevel isoLevel);
    }
}
View Code

OrmClient类:IOrmClient接口的实现

技术分享
using ServiceStack.Data;
using ServiceStack.Logging;
using ServiceStack.Orm.Extension.Interface;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Extension;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;

namespace ServiceStack.Orm.Extension.Imples
{
    public partial class OrmClient : IOrmClient
    {
        private IDbConnectionFactory _dbFactory;
        private IOrmLiteDialectProvider _dialectProvider;
        private int _dbConnectionDepth;
        private IDbConnection _dbConnection;
        private ILog log = LogManager.LogFactory.GetLogger(typeof(OrmClient));

        public OrmClient(string connectionString, IOrmLiteDialectProvider dialectProvider)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (dialectProvider == null)
                throw new ArgumentNullException("dialectProvider");
            _dbFactory = new OrmLiteConnectionFactory(connectionString, dialectProvider);
            this._dialectProvider = dialectProvider;
            OrmLiteConfig.ExecFilter = new OrmLiteExecFilterExt();
        }

        public T Execute<T>(Func<IDbConnection, T> action)
        {
            try
            {
                OpenDBConnection();
                return action(_dbConnection);
            }
            catch (Exception x)
            {
                string errMessage = string.Format("数据库操作异常,最后执行的SQL语句为:{0},异常信息为:{1}", _dbConnection.GetLastSql(), x.ToString());
                log.Error(errMessage);
                return default(T);
            }
            finally
            {
                CloseDBConnection();
            }
        }

        public void Execute(Action<IDbConnection> action)
        {
            try
            {
                OpenDBConnection();
                action(_dbConnection);
            }
            catch (Exception x)
            {
                string errMessage = string.Format("数据库操作异常,最后执行的SQL语句为:{0},异常信息为:{1}", _dbConnection.GetLastSql(), x.ToString());
                log.Error(errMessage);
            }
            finally
            {
                CloseDBConnection();
            }
        }

        public SqlExpression<T> From<T>() where T : IDBEntity, new()
        {
            return _dialectProvider.SqlExpression<T>();
        }

        public long Insert<T>(T entity, bool selectIdentity = false) where T : IDBEntity, new()
        {
            if (entity == null)
                return 0L;
            return Execute<long>(db => db.Insert<T>(entity, selectIdentity));
        }

        public void InsertAll<T>(IEnumerable<T> entities) where T : IDBEntity, new()
        {
            if (entities != null && entities.Any<T>())
            {
                Execute(db => db.InsertAll(entities));
            }
        }

        public long Update<T>(T entity) where T : IDBEntity, new()
        {
            if (entity == null)
                return 0L;
            return Execute<long>(db => db.Update<T>(entity));
        }

        public long Update<T>(T entity, Expression<Func<T, bool>> where) where T : IDBEntity, new()
        {
            if (entity == null)
                return 0L;
            return Execute<long>(db => db.Update<T>(entity, where));
        }

        public long Update<T>(T entity, Expression<Func<T, object>> onlyFields = null, Expression<Func<T, bool>> where = null) where T : IDBEntity, new()
        {
            return Execute(db => db.UpdateOnly<T>(entity, onlyFields, where));
        }

        public void UpdateAll<T>(IEnumerable<T> entities) where T : IDBEntity, new()
        {
            if (entities != null && entities.Any<T>())
            {
                Execute(db => db.UpdateAll<T>(entities));
            }
        }

        public long Delete<T>(SqlExpression<T> where) where T : IDBEntity, new()
        {
            return Execute(db => db.Delete<T>(where));
        }

        public long Delete<T>(Expression<Func<T, bool>> where) where T : IDBEntity, new()
        {
            return Execute(db => db.Delete<T>(where));
        }

        public List<T> Select<T>(SqlExpression<T> expression) where T : IDBEntity, new()
        {
            return Execute(db => db.Select<T>(expression));
        }

        public List<T> Select<T>(Expression<Func<T, bool>> predicate) where T : IDBEntity, new()
        {
            return Execute(db => db.Select<T>(predicate));
        }

        public List<T> SelectAsync<T>(Expression<Func<T, bool>> predicate) where T : IDBEntity, new()
        {
            return Execute(db => db.Select<T>(predicate));
        }

        public IEnumerable<T> SelectLazy<T>(SqlExpression<T> expression) where T : IDBEntity, new()
        {
            return Execute(db => db.SelectLazy<T>(expression));
        }

        public long Count<T>(SqlExpression<T> expression) where T : IDBEntity, new()
        {
            return Execute(db => db.Count<T>(expression));
        }

        public bool Exist<T>(SqlExpression<T> expression) where T : IDBEntity, new()
        {
            return Execute(db => db.Exists<T>(expression));
        }

        public T Scalar<T>(SqlExpression<T> expression) where T : IDBEntity, new()
        {
            return Execute(db => db.Scalar<T>(expression));
        }

        public int ExecuteSql(string sql, object dbParams = null)
        {
            if (dbParams == null)
                return Execute(db => db.ExecuteSql(sql));
            return Execute(db => db.ExecuteSql(sql, dbParams));
        }

        #region 事物

        public bool InvokeTransaction(IEnumerable<Func<long>> actions)
        {
            return InvokeTransaction(() =>
            {
                foreach (var action in actions)
                {
                    if (action() <= 0)
                        return false;
                }
                return true;
            });
        }

        public bool InvokeTransaction(Func<bool> action)
        {
            return Execute(db =>
            {
                bool isTranSuccess = false;
                using (var trans = db.BeginTransaction())
                {
                    try
                    {
                        isTranSuccess = action();
                    }
                    catch (Exception x)
                    {
                        string errorMessage = string.Format("事务操作异常,最后执行的SQL语句为:{0},异常信息为:{1}", db.GetLastSql(), x.ToString());
                        log.Error(errorMessage);
                    }
                    if (isTranSuccess)
                        trans.Commit();
                    else
                        trans.Rollback();
                }
                return isTranSuccess;
            });
        }

        public bool InvokeTransaction(Func<bool> action, IsolationLevel isoLevel)
        {
            return Execute(db =>
            {
                bool isTranSuccess = false;
                using (var trans = db.BeginTransaction(isoLevel))
                {
                    try
                    {
                        isTranSuccess = action();
                    }
                    catch (Exception x)
                    {
                        string errorMessage = string.Format("事务操作异常,最后执行的SQL语句为:{0},异常信息为:{1}", db.GetLastSql(), x.ToString());
                        log.Error(errorMessage);
                    }
                    if (isTranSuccess)
                        trans.Commit();
                    else
                        trans.Rollback();
                }
                return isTranSuccess;
            });
        }

        #endregion

        #region DBConnection Manager
        private void OpenDBConnection()
        {
            if (_dbConnectionDepth == 0)
            {
                _dbConnection = _dbFactory.CreateDbConnection();

                if (_dbConnection.State == ConnectionState.Broken)
                    _dbConnection.Close();
                else if (_dbConnection.State == ConnectionState.Closed)
                    _dbConnection.Open();
            }
            _dbConnectionDepth++;
        }

        private void CloseDBConnection()
        {
            if (_dbConnectionDepth > 0)
            {
                _dbConnectionDepth--;
                if (_dbConnectionDepth == 0)
                {
                    _dbConnection.Dispose();
                    _dbConnection = null;
                }
            }
        }
        #endregion
    }
}
View Code

 

ServiceStack.OrmLite简单扩展

标签:

原文地址:http://www.cnblogs.com/Jabben/p/5672861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!