ServiceStack.OrmLite简单扩展

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();
        }
    }
}

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

using System;
namespace ServiceStack.Orm.Extension.Interface
{
    public interface IDBEntity
    {
    }
}

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);
    }
}

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
    }
}

时间: 2024-10-17 18:29:13

ServiceStack.OrmLite简单扩展的相关文章

ServiceStack.OrmLite中的一些&quot;陷阱&quot;(1)

使用过ServiceStack.Ormlite的人都应该知道,其作为一个轻量级的ORM,使用的便捷度非常高,用起来就一个字:爽!而支撑其便捷度的,是库内大量地使用了扩展方法及静态变量. 首先先从源头入手分析(以下以Sqlite为例): OrmLiteConfig.DialectProvider = SqliteOrmLiteDialectProvider.Instance; using (IDbConnection db = "~/db.sqlite".MapAbsolutePath(

ServiceStack.OrmLite中的一些&quot;陷阱&quot;(2)

注:此系列不是说ServiceStack.OrmLite的多个陷阱,这仅仅个人认为是某一个陷阱(毕竟我踩坑了)而引发的思考. 前文说到了项目需要使用两种不同的数据库语言,虽说前文问题已基本解决了,但是我发现OrmLite在设计上有需要改进的地方.正如前面提到的OrmLite为了开发的便捷性,ORM所需要生成SQL语句DialectProvider设置为静态属性(尽管使用了线程安全),但是这样的话DialectProvider便与线程上下文产生耦合. 而一个更优的方法,则是使用代理.第一次对代理产

ServiceStack OrmLite 连接Sqlserver数据库

技术交流群:665060698 ServiceStack是一个.net的服务类库,包含的数据处理非常丰富,执行效率也非常高, 但ServiceStack也不止是用来写服务,也可以引用其中的dll进行数据库的连接操作,ServiceStack OrmLite支持的数据类型也很多,包括Sqlserver.Mysql.Postgresql.Sqlite等,下边分享一个 简单 ServiceStack OrmLite的连接sqlserver数据库,并获取数据.  var _sqlserverFla = 

简单扩展让beetl HTML标签支持父子嵌套

默认情况下,Beetl的html标签并不支持父子嵌套,就像类似jsp标签那样,父标签需要知道子标签的信息,子标签也需要知道父标签信息.但是beetl只需要简单扩展,就能完成嵌套标签支持. 首先看一个最终的使用效果,实现俩个html标签table.tag,tr.tag.可以在页面上这么用: <#table data ="${userList}"> <#tr class="3c" name="name"> 名称 </#t

ServiceStack.OrmLite 入门(一)

软件环境: Win7 x64 SP1 SQL Server 2008r2 Visual Studio 2017 Professional 目标:取出示例数据库 ReportServer 的表 Roles 中的所有记录并显示. 步骤: 一.添加软件包 使用NuGet添加以下软件包: ServiceStack ServiceStack.OrmLite 二.定义表类 根据表Roles来定义对应的C#类: [Serializable] [Alias("Roles")] public class

ServiceStack.OrmLite破解

在 ServiceStack.OrmLite下的 OrmLiteConfigExtensions 第199行把这句注释掉就可以了 //LicenseUtils.AssertValidUsage(LicenseFeature.OrmLite, QuotaType.Tables, typeModelDefinitionMap.Count);

ServiceStack.OrmLite 调用存储过程

最近在做关于ServiceStack.OrmLite调用存储过程时,有问题.发现ServiceStack.OrmLite不能调用存储过程,或者说不能实现我想要的需求.在做分页查询时,我需要传入参数传出参数. ServiceStack.OrmLite 调用存储过程代码: 存储过程:usp_GetCarComponentsList 传入参数:@page,@limit 传出参数:@pageCount ,@totalCount 问题描述:参数传入在数据库中不能接收,不知道是写法问题,还是其他原因.即便传

递归扩展变量和简单扩展变量

1 递归扩展变量和简单扩展变量的区别 最大的区别在于,递归扩展变量等号右边的表达式里面的变量要等到该递归变量被用的时候再去扩展,而简单变量的话,在读取makefile的时候就已经扩展了. 并且简单扩展变量有前后关系,简单扩展变量只能用到在其前面定义的变量,而不能用到在其后面定义的变量.而递归扩展变量,要用的时候,需要扩展的时候,可以一直扩展到不能扩展为止,即递归扩展. 2 例子 foo := $(bar) bar = aaa all:;echo $(foo) 输出为空,因为在给foo赋值扩展等号

对lua的简单扩展,使它能快速关联C++的数据。

很早的时候,我纠结过一件事,假如,我在C++公开给脚本的接口中,要使用C++里的某一个对象,并且,我的程序中有很多个不同的lua虚拟机,每一个虚拟机要关联一个C++对象,并且这是多线程的,那么这时候应该如何快速的利用lua_State指针来定位到对象指针呢? 以前我没有能力读懂lua的源码,也可以说不知道关键部分如何操作,我当时的做法,是利用临界区和std::map来解决问题的,很明显这个方式的效率很低很低. 现在有能力读lua源码了,当然有更有效的解决办法了,因为在我们利用lua的过程中,lu