Sqlsugar帮助类

SqlsugarHelper

  public class SqlsugarHelper
    {

        static string ConnectionString = string.Empty;
        static SqlSugar.DbType dbtype = SqlSugar.DbType.SqlServer;
        SqlsugarHelper( SqlSugar.DbType dbtype)
        {
            
            if(dbtype== SqlSugar.DbType.SqlServer)
            {
                SqlsugarHelper.ConnectionString = ConnTools.init().GetSqlServerConn();
            }else if(dbtype == SqlSugar.DbType.Oracle)
            {
                SqlsugarHelper.ConnectionString = ConnTools.init().GetOracleConn();
            }
            SqlsugarHelper.dbtype = dbtype;

        }
        private static SqlsugarHelper _Singleton = null;
        private static readonly object Singleton_Lock = new object();
        public static SqlsugarHelper Init(SqlSugar.DbType dbtype= SqlSugar.DbType.SqlServer)
        {

            if (_Singleton == null) //双if +lock
            {
                lock (Singleton_Lock)
                {
                    if (_Singleton == null)
                    {
                        //创建对象
                        _Singleton = new SqlsugarHelper(dbtype);

                    }
                }
            }
            return _Singleton;
        }
        /// 
        /// 获取数据库连接实体,禁止使用静态变量对接
        /// 
        public static SqlSugarClient Instance
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(ConnectionString))
                {
                    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = ConnectionString,
                        DbType = dbtype,//设置数据库类型
                        IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
                        InitKeyType = InitKeyType.SystemTable,//从数据库系统表读取主键信息中(InitKeyType.Attribute从实体特性中读取主键自增列信息)
                    });

                    //  调试SQL,AOP ,日志
                    db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
                    {
#if DEBUG
                        //获取执行后的总毫秒数
                        double sqlExecutionTotalMilliseconds = db.Ado.SqlExecutionTime.TotalMilliseconds;
#endif
                    };
                    db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件。可在这里查看生成的sql
                    {
#if DEBUG
                        string tempSQL = LookSQL(sql, pars);
#endif
                    };
                    db.Aop.OnError = (exp) =>
                    {
                        //exp.sql exp.parameters 可以拿到参数和错误Sql  
                        StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter参数为:");
                        var parametres = exp.Parametres as SugarParameter[];
                        if (parametres != null)
                        {
                            sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
                        }

                        StringBuilder sb_error = new StringBuilder();
                        sb_error.AppendLine("SqlSugarClient执行sql异常信息:" + exp.Message);
                        sb_error.AppendLine("###赋值后sql:" + LookSQL(exp.Sql, parametres));
                        sb_error.AppendLine("###带参数的sql:" + exp.Sql);
                        sb_error.AppendLine("###参数信息:" + sb_SugarParameterStr.ToString());
                        sb_error.AppendLine("###StackTrace信息:" + exp.StackTrace);
                        };

                    db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
                    {
                        //判断update或delete方法是否有where条件。如果真的想删除所有数据,请where(p=>true)或where(p=>p.id>0)
                        if (sql.TrimStart().IndexOf("delete ", StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
                            {
                                throw new Exception("delete删除方法需要有where条件!!");
                            }
                        }
                        else if (sql.TrimStart().IndexOf("update", StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0 && sql.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) <= 0)
                            {
                                throw new Exception("update更新方法需要有where条件!!");
                            }
                        }

                        return new KeyValuePair<string, SugarParameter[]>(sql, pars);
                    };

                    //db.Aop.OnDiffLogEvent = it =>// 数据库操作前和操作后的数据变化。
                    //{
                    //    var editBeforeData = it.BeforeData;
                    //    var editAfterData = it.AfterData;
                    //    var sql = it.Sql;
                    //    var parameter = it.Parameters;
                    //    var data = it.BusinessData;
                    //    var time = it.Time;
                    //    var diffType = it.DiffType;//枚举值 insert 、update 和 delete 用来作业务区分

                    //    //你可以在这里面写日志方法
                    //};

                    //db.Ado.CommandTimeOut //设置sql执行超时等待时间(毫秒单位)
                    //db.Ado.Connection.ConnectionTimeout //设置数据库连接等待时间(毫秒单位)

                    return db;
                }
                else
                {
                    return null;
                }

            }
        }

        public static SqlSugarScope _Instance
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(ConnectionString))
                {
                    SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
                    {
                        ConnectionString = ConnectionString,
                        DbType = dbtype,//设置数据库类型
                        IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
                        InitKeyType = InitKeyType.SystemTable,//从数据库系统表读取主键信息中(InitKeyType.Attribute从实体特性中读取主键自增列信息)
                    });

                    //  调试SQL,AOP ,日志
                    db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
                    {
#if DEBUG
                        //获取执行后的总毫秒数
                        double sqlExecutionTotalMilliseconds = db.Ado.SqlExecutionTime.TotalMilliseconds;
#endif
                    };
                    db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件。可在这里查看生成的sql
                    {
#if DEBUG
                        string tempSQL = LookSQL(sql, pars);
#endif
                    };
                    db.Aop.OnError = (exp) =>//执行SQL 错误事件
                    {
                        //exp.sql exp.parameters 可以拿到参数和错误Sql  
                        StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter参数为:");
                        var parametres = exp.Parametres as SugarParameter[];
                        if (parametres != null)
                        {
                            sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
                        }

                        StringBuilder sb_error = new StringBuilder();
                        sb_error.AppendLine("SqlSugarClient执行sql异常信息:" + exp.Message);
                        sb_error.AppendLine("###赋值后sql:" + LookSQL(exp.Sql, parametres));
                        sb_error.AppendLine("###带参数的sql:" + exp.Sql);
                        sb_error.AppendLine("###参数信息:" + sb_SugarParameterStr.ToString());
                        sb_error.AppendLine("###StackTrace信息:" + exp.StackTrace);


                    };

                    db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
                    {
                        //判断update或delete方法是否有where条件。如果真的想删除所有数据,请where(p=>true)或where(p=>p.id>0)
                        if (sql.TrimStart().IndexOf("delete ", StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
                            {
                                throw new Exception("delete删除方法需要有where条件!!");
                            }
                        }
                        else if (sql.TrimStart().IndexOf("update ", StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0 && sql.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) <= 0)
                            {
                                throw new Exception("update更新方法需要有where条件!!");
                            }
                        }

                        return new KeyValuePair<string, SugarParameter[]>(sql, pars);
                    };

                    //db.Aop.OnDiffLogEvent = it =>// 数据库操作前和操作后的数据变化。
                    //{
                    //    var editBeforeData = it.BeforeData;
                    //    var editAfterData = it.AfterData;
                    //    var sql = it.Sql;
                    //    var parameter = it.Parameters;
                    //    var data = it.BusinessData;
                    //    var time = it.Time;
                    //    var diffType = it.DiffType;//枚举值 insert 、update 和 delete 用来作业务区分

                    //    //你可以在这里面写日志方法
                    //};

                    //db.Ado.CommandTimeOut //设置sql执行超时等待时间(毫秒单位)
                    //db.Ado.Connection.ConnectionTimeout //设置数据库连接等待时间(毫秒单位)

                    return db;
                }
                else
                {
                    return null;
                }

            }
        }
        /// 
        /// 查看赋值后的sql
        /// 
        /// 
        /// 参数
        /// 
        private static string LookSQL(string sql, SugarParameter[] pars)
        {
            if (pars == null || pars.Length == 0) return sql;

            StringBuilder sb_sql = new StringBuilder(sql);
            var tempOrderPars = pars.Where(p => p.Value != null).OrderByDescending(p => p.ParameterName.Length).ToList();//防止 @par1错误替换@par12
            for (var index = 0; index < tempOrderPars.Count; index++)
            {
                sb_sql.Replace(tempOrderPars[index].ParameterName, "'" + tempOrderPars[index].Value.ToString() + "'");
            }

            return sb_sql.ToString();
        }

        #region 获取实体
        /// 
        /// 获取一个实体
        /// 
        /// 
        /// 主键
        /// 
        public T GetModel<T>(object id)
        {
            return GetModel<T>(id, SqlsugarHelper.Instance);
        }
        /// 
        /// 返回数据库连接对象
        /// 
        /// 
        public SqlSugarClient GetClient()
        {
            return SqlsugarHelper.Instance;
        }
        /// 
          /// 返回数据库连接对象(保证线程安全避免偶发性错误)
          /// 
          /// 
        public SqlSugarScope _GetClient()
        {
            return SqlsugarHelper._Instance;
        }
        /// 
        /// 获取一个实体
        /// 
        /// 
        /// 主键
        /// 表名称
        /// 
        public T GetModel<T>(string TableName, Expression<Func<T, bool>> expressionWhere)
        {
            return GetModel<T>(TableName, expressionWhere, SqlsugarHelper.Instance);
        }
        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 
        public List<T> GetModelList<T>()
        {
            return GetModelList<T>(SqlsugarHelper.Instance);
        }
        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 表名称
        /// 
        public List<T> GetModelList<T>(string TableName)
        {
            return GetModelList<T>(SqlsugarHelper.Instance,TableName);
        }
         /// 
        /// 多条件查询
        /// 
        /// 
        /// 条件
        /// 表名称
        /// 
        public List<T> Queryable<T>(Expression<Func<T, bool>> expression, string TableName)
        {
           return  this.GetClient().Queryable<T>().AS(TableName).Where(expression).ToList();
        }
        /// 
        /// 执行原生sql语句
        /// 
        /// 原生sql语句
        /// 参数
        /// 
        public DataTable GetDataTable(string sql, List<SugarParameter> sugars = null)
        {
            return GetDataTable(sql, SqlsugarHelper.Instance, sugars);
        }
      /// 
      /// 执行sql语句返回datatable
      /// 
      /// 原生sql语句
      /// 数据库连接
      /// 参数
      /// 
        public DataTable GetDataTable(string sql, SqlSugarClient db, List<SugarParameter> sugars = null)
        {
          return  db.Ado.GetDataTable(sql, sugars);
        }
        
        /// 
        /// 获取一个实体
        /// 
        /// 
        /// 主键
        /// 
        /// 
        private T GetModel<T>(object id, ISqlSugarClient db)
        {
            return db.Queryable<T>().InSingle(id);
        }
       
        /// 
        /// 获取一个实体
        /// 
        /// 
        /// 主键
        /// 
        /// 
        public T GetModel<T>(string
             TableName, Expression<Func<T, bool>> expressionWhere, ISqlSugarClient db)
        {
            return db.Queryable<T>().AS(TableName).Where(expressionWhere).First();
        }
        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 
        /// 
        public List<T> GetModelList<T>(ISqlSugarClient db)
        {
            return db.Queryable<T>().ToList();
        } 
        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 
        /// 
        public List<T> GetModelList<T>(ISqlSugarClient db,string TableName)
        {
            return db.Queryable<T>().AS(TableName).ToList();
        }

        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 表名称
        /// 
        public List<T> GetModelList<T>(Expression<Func<T, bool>> expressionWhere)
        {
            return GetModelList<T>(expressionWhere, SqlsugarHelper.Instance);
        }

        /// 
        /// 根据条件查询多条数据
        /// 
        /// 
        /// 条件表达式
        /// (事务的db对象)
        /// 
        public List<T> GetModelList<T>(Expression<Func<T, bool>> expressionWhere, SqlSugarClient db)
        {
            return db.Queryable<T>().Where(expressionWhere).ToList();
        }
        /// 
        /// 获取多个实体
        /// 
        /// 
        /// 主键
        /// 表名称
        /// 
        public List<T> GetModelList<T>(string TableName, Expression<Func<T, bool>> expressionWhere)
        {
            return GetModelList<T>(TableName, expressionWhere, SqlsugarHelper.Instance);
        }
        /// 
        /// 根据条件查询多条数据
        /// 
        /// 
        /// 表名称
        /// 条件表达式
        /// (事务的db对象)
        /// 
        public List<T> GetModelList<T>(string TableName, Expression<Func<T, bool>> expressionWhere, ISqlSugarClient db) 
        {
            return db.Queryable<T>().AS(TableName).Where(expressionWhere).ToList();
        }


      
        #region 从缓存中获取一个实体
        /// 
        /// 从缓存中获取一个实体
        /// 
        /// 
        /// 主键
        /// 
        public T GetModel_WithCache<T>(object id)
        {
            return GetModel_WithCache<T>(id, Instance);
        }

        /// 
        /// 从缓存中获取一个实体
        /// 
        /// 
        /// 主键
        /// 
        /// 
        public T GetModel_WithCache<T>(object id, SqlSugarClient db)
        {
            return db.Queryable<T>().WithCache().InSingle(id);
        }
        #endregion

        #endregion

        #region 添加
        /// 
        /// 添加实体(实体名称和表名称不一致是使用)
        /// 
        /// 实体类型
        /// 实体
        /// 表名称
        /// 返回添加成功条数
        public int InsertModel<T>(T t, string TableName) where T : class, new()
        {
            return InsertModel(t, TableName, SqlsugarHelper.Instance);
        }
        /// 
        /// 新增或修改实体
        /// 
        /// 实体类型
        /// 实体
        /// 表名
        /// 条件列
        /// 指定更新列(互斥)
        /// 忽略更新列(互斥)
        /// 
        public int InsOrUpadteModel<T>(T t,string TableName, Expression<Func<T, object>> columns, Expression<Func<T, object>> UpdateColumns = null, Expression<Func<T, object>> ignoreColumns=null) where T : class, new()
        {
            return InsOrUpadteModel(t, TableName, columns, SqlsugarHelper.Instance, UpdateColumns,ignoreColumns);
        }  
        /// 
        /// 新增或修改实体
        /// 
        /// 实体类型
        /// 实体
        /// 
        public int InsOrUpadteModel<T>(T t) where T : class, new()
        {
            return InsOrUpadteModel(t, SqlsugarHelper.Instance);
        }
        /// 
        /// 添加实体(实体名称和表名称不一致是使用)
        /// 
        /// 实体类型
        /// 实体
        /// 表名称
        /// 数据库连接字符串
        /// 
        public int InsertModel<T>(T t, string TableName, ISqlSugarClient db) where T : class, new()
        {
            return db.Insertable(t).AS(TableName).ExecuteCommand();
        }
        /// 
        /// 新增或修改实体
        /// 
        /// 实体类型
        /// 实体
        /// 表名称
        /// 设置主键
        /// 连接对象
        /// 
        public int InsOrUpadteModel<T>(T t,string TableName, Expression<Func<T, object>> columns, SqlSugarClient db) where T : class, new()
        {
            int count = 0;
            var x = db.Storageable(t).As(TableName).WhereColumns(columns).ToStorage(); //将数据进行分组 
            count+= x.AsInsertable.ExecuteCommand(); //执行插入 (可以换成雪花ID和自增)
            count+= x.AsUpdateable.IgnoreColumns().ExecuteCommand(); //执行更新 
            return count;
        }
        /// 
        /// 更新或新增数据
        /// 
        /// 
        /// 
        /// 表名称
        /// 条件列
        /// 指定更新列(互斥)
        /// 忽略跟新列(互斥)
        /// 
        /// 
        private int InsOrUpadteModel<T>(T t, string TableName, Expression<Func<T, object>> columns, ISqlSugarClient db, Expression<Func<T, object>> UpdateColumns=null, Expression<Func<T, object>> ignoreColumns=null) where T : class, new()
        {
            int count = 0;
            var x = db.Storageable(t).As(TableName).WhereColumns(columns).ToStorage(); //将数据进行分组 
            count += x.AsInsertable.ExecuteCommand(); 
            if(UpdateColumns!=null && ignoreColumns==null)
            {
                count += x.AsUpdateable.UpdateColumns(UpdateColumns).ExecuteCommand(); //执行更新 
            }
           else if(ignoreColumns!=null && UpdateColumns==null)
            {
                count += x.AsUpdateable.IgnoreColumns(ignoreColumns).ExecuteCommand(); //执行更新 
            }
            else
            {
                count += x.AsUpdateable.ExecuteCommand(); //执行更新 
            }
            
            return count;
        }
        /// 
        /// 新增或修改实体
        /// 
        /// 实体类型
        /// 实体
        /// 连接对象
        /// 
        public int InsOrUpadteModel<T>(T t, SqlSugarClient db) where T : class, new()
        {
            int count = 0;
            var x = db.Storageable(t).ToStorage(); //将数据进行分组 
            count += x.AsInsertable.ExecuteCommand(); //执行插入 (可以换成雪花ID和自增)
            count += x.AsUpdateable.ExecuteCommand(); //执行更新 
            return count;
        }

        /// 
        ///不保证线程安全(有则更新无则插入)
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public int BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns) where T : class, new()
        {
            return BulkCopyModel(t, TableName, WhereColumns, SqlsugarHelper.Instance);
        }
        /// 
        /// 保证线程安全(有则更新无则插入)
        /// 
        /// 
        /// 
        /// 
        /// 分组依据列
        /// xiu依据列
        /// 
        public int _BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns) where T : class, new()
        {
            return BulkCopyModel(t, TableName, WhereColumns, SqlsugarHelper._Instance);
        }
        /// 
        /// 大量数据更新(如果有则更新没有则插入)
        /// 
        /// 模型
        /// 数据
        /// 表名
        /// 数据库连接
        /// 
        public int BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns, ISqlSugarClient db) where T : class, new()
        {

            var x = db.Storageable<T>(t).As(TableName).WhereColumns(WhereColumns).ToStorage();
            int I = x.AsInsertable.ExecuteCommand(); //执行插入
            int U = x.AsUpdateable.ExecuteCommand();
            //int I = x.BulkCopy();//不存在插入
            //int U = x.BulkUpdate();//存在更新

            return I + U;
        } 
        /// 
        /// 批量更新或插入(不保证线程安全)
        /// 
        /// 
        /// 
        /// 表名称
        /// 条件列
        /// 
        /// 
        //public int BulkCopyModel(List t, string TableName, Expression> WhereColumns, SqlSugarClient db) where T : class, new()
        //{
        //    var x = db.Storageable(t).As(TableName).WhereColumns(WhereColumns).ToStorage();
        //    int I = x.BulkCopy();//不存在插入
        //    int U = x.BulkUpdate();//存在更新

        //    return I + U;
        //}
        /// 
        /// 批量数据插入(不检查数据是否已存在)
        /// 
        /// 模型类型
        /// 数据对象
        /// 表名称
        /// 受影响行数
        public int BulkInsertModel<T>(List<T> t, string TableName) where T : class, new()
        {
            return BulkInsertModel(t, TableName, SqlsugarHelper.Instance);
        }
        /// 
        /// 批量数据插入(不检查数据是否已存在)
        /// 
        /// 模型
        /// 
        /// 表名
        /// 
        /// 
        private int BulkInsertModel<T>(List<T> t, string TableName, SqlSugarClient db) where T : class, new()
        {
            return db.Fastest<T>().AS(TableName).BulkCopy(t);
        }
        /// 
        /// 添加实体数据,并返回主键值(主键为自增int类型id,实体需要设置主键特性(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// 
        public int InsertModel<T>(T t) where T : class, new()
        {
            return InsertModel(t, SqlsugarHelper.Instance);
        }
        /// 
        /// 插入数据五百条数据内最快
        /// 
        /// 
        /// 
        /// 
        /// 
        public int InsertModels<T>(List<T> t, string TableName, Expression<Func<T, object>> ignoreColumns) where T : class, new()
        {

            return InsertModels(t, TableName, ignoreColumns, SqlsugarHelper.Instance);
        }
        /// 
        /// 添加实体数据,并返回主键值(主键为自增int类型id,实体需要设置主键特性)(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public int InsertModel<T>(T t, SqlSugarClient db) where T : class, new()
        {
            //Where(true/*不插入null值的列*/,false/*不插入主键值*/)
            return db.Insertable(t).
                //IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
                IgnoreColumns(true, false).ExecuteReturnIdentity();
        }
        /// 
        /// 添加实体数据,并返回主键值(主键为自增long类型id,实体需要设置主键特性(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// 
        public long InsertModel_BigIdentity<T>(T t) where T : class, new()
        {
            return InsertModel_BigIdentity(t, SqlsugarHelper.Instance);
        }
        /// 
        /// 添加实体数据,并返回主键值(主键为自增long类型id,实体需要设置主键特性)(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public long InsertModel_BigIdentity<T>(T t, SqlSugarClient db) where T : class, new()
        {
            //Where(true/*不插入null值的列*/,false/*不插入主键值*/)
            return db.Insertable(t).
                //IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
                IgnoreColumns(true, false).ExecuteReturnBigIdentity();
        }
        /// 
        /// 批量插入五百条内速度最快
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private int InsertModels<T>(List<T> t, string TableName, Expression<Func<T, object>> ignoreColumns, ISqlSugarClient db) where T : class, new()
        {
            return db.Insertable(t).AS(TableName).IgnoreColumns(ignoreColumns).UseParameter().ExecuteCommand();
        }
        #region  删除缓存
        /// 
        /// 添加实体数据,删除缓存,并返回主键值(主键为自增int类型id,实体需要设置主键特性(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// 
        public int InsertModel_RemoveDataCache<T>(T t) where T : class, new()
        {
            return InsertModel_RemoveDataCache(t, SqlsugarHelper.Instance);
        }

        /// 
        /// 添加实体数据,删除缓存,并返回主键值(主键为自增int类型id,实体需要设置主键特性)(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public int InsertModel_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
        {
            //Where(true/*不插入null值的列*/,false/*不插入主键值*/)
            return db.Insertable(t).
                //IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
                IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnIdentity();
        }

        /// 
        /// 添加实体数据,并返回主键值(主键为自增long类型id,实体需要设置主键特性(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// 
        public long InsertModel_BigIdentity_RemoveDataCache<T>(T t) where T : class, new()
        {
            return InsertModel_BigIdentity_RemoveDataCache(t, SqlsugarHelper.Instance);
        }

        /// 
        /// 添加实体数据,并返回主键值(主键为自增long类型id,实体需要设置主键特性)(为null字段不更新,注意model有默认值的情况)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public long InsertModel_BigIdentity_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
        {
            //Where(true/*不插入null值的列*/,false/*不插入主键值*/)
            return db.Insertable(t).
                //IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
                IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnBigIdentity();
        }
        #endregion

        #endregion

        #region 更新
      
             /// 
             /// 根据主键更新实体(指定字段不更新,注意model有默认值的情况),返回影响条数(实体字段要有主键特性)
             /// 
             /// 
             /// 
             /// 表名
             /// 指定更新列
             /// 忽略更新列
             /// 
        public int UpdateModelByKey<T>(T t, string TableName, Expression<Func<T, object>> UpdateColumns = null, Expression<Func<T, object>> ignoreColumns = null) where T : class, new()
        {
            return UpdateModelByKey(t, TableName, SqlsugarHelper.Instance, ignoreColumns, UpdateColumns);
        } 
        /// 
        /// 根据主键更新实体(为null字段不更新,注意model有默认值的情况),返回影响条数(实体字段要有主键特性)
        /// 
        /// 
        /// 
        /// 
        public int UpdateModel <T>(T t, string TableName) where T : class, new()
        {
            return UpdateModel(t, TableName, SqlsugarHelper.Instance);
        }

        /// 
        /// 根据主键更新实体,返回影响条数(实体字段要有主键特性)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 指定更新列(互斥)
        /// 忽略更新列(互斥)
        /// 
        public int UpdateModelByKey<T>(T t, string TableName, SqlSugarClient db, Expression<Func<T, object>> updateColumns = null, Expression<Func<T, object>> ignoreColumns = null) where T : class, new()
        {
            //字段null,不进行更新
            if (updateColumns != null && ignoreColumns == null)
            {
                return db.Updateable(t).AS(TableName).UpdateColumns(ignoreColumns).ExecuteCommand();
            }
            else if(ignoreColumns!=null && updateColumns==null)
            {
                return db.Updateable(t).AS(TableName).IgnoreColumns(ignoreColumns).ExecuteCommand();
            }
            else
            {
                //字段null,不进行更新
                return db.Updateable(t).AS(TableName).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
            }
           
        }
        /// 
        /// 根据主键更新实体,返回影响条数(实体字段要有主键特性)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public int UpdateModel<T>(T t, string TableName, SqlSugarClient db) where T : class, new()
        {
            //字段null,不进行更新
            return db.Updateable(t).AS(TableName).ExecuteCommand();
        }
       
        /// 
        /// 根据条件表达式更新实体(为null字段不更新,注意model有默认值的情况),返回影响条数
        /// 
        /// 
        /// 
        /// 条件表达式
        /// 
        public int UpdateModelsIgnoreNull<T>(T t, Expression<Func<T, bool>> expressionWhere) where T : class, new()
        {
            return UpdateModelsIgnoreNull(t, expressionWhere, SqlsugarHelper.Instance);
        }

        /// 
        /// 根据条件表达式更新实体(为null字段不更新,注意model有默认值的情况),返回影响条数
        /// 
        /// 
        /// 
        /// 条件表达式
        /// (事务的db对象)
        /// 
        public int UpdateModelsIgnoreNull<T>(T t, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
        {
            return db.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true).Where(expressionWhere).ExecuteCommand();
        }

        /// 
        /// 根据条件表达式更新实体(指定要更新的列),返回影响条数
        /// 
        /// 
        /// 模型
        /// 数据库中的表名称
        /// 需要更新的字段
        /// 条件表达式
        /// 
        public int UpdateModels<T>(T t, string TableName, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
        {
            return UpdateModels<T>(t, TableName, columns, expressionWhere, SqlsugarHelper.Instance);
        }

        /// 
        /// 根据条件表达式更新实体(指定要更新的列),返回影响条数
        /// 
        /// 
        /// 
        /// 数据库中的表名
        /// 需要更新的字段表达式
        /// 条件表达式
        /// (事务的db对象)
        /// 
        public int UpdateModels<T>(T t, string TableName, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
        {

            return db.Updateable(t).AS(TableName).UpdateColumns(columns).Where(expressionWhere).ExecuteCommand();

        }

        /// 
        /// 动态更新
        /// 
        /// 
        /// 写入要更新的字段
        /// where条件表达式
        /// 
        public int Update<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
        {
            return Update<T>(columns, expressionWhere, SqlsugarHelper.Instance);
            /* 调用示例
            Update(p => new Entity.SysAdmin { photo = photo, Password = newPwd }
               ,p => p.ID == sm.id && p.Password == oldPwd) > 0;
            */
        }

        /// 
        /// 动态更新
        /// 
        /// 
        /// 要更新的字段
        /// where条件表达式
        /// 
        /// 
        public int Update<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
        {
            return db.Updateable<T>().SetColumns(columns).
                //IgnoreColumns(ignoreAllNullColumns: true).//不能加此方法,会有“CommandText 属性尚未初始化”异常
                Where(expressionWhere).ExecuteCommand();
            /* 调用示例
             Update(p => new Entity.SysAdmin { photo = photo, Password = newPwd }
                ,p => p.ID == sm.id && p.Password == oldPwd ,db) > 0;
             */
        }
        /// 
        /// 有主键批量更新
        /// 
        /// 
        /// 
        /// 表名称
        /// 条件列
        /// 更新列
        /// 
        public int BulkUpdata<T>(List<T> t, string TableName, string[] whereColumns = null, string[] updateColumns = null) where T : class, new()
        {
            return BulkUpdata(t, TableName, SqlsugarHelper.Instance, whereColumns, updateColumns);
        }
        /// 
        /// 有主键批量更新
        /// 
        /// 
        /// 
        /// 表名称
        /// 数据库连接
        /// 条件列
        /// 更新列
        /// 
        public int BulkUpdata<T>(List<T> t, string TableName, SqlSugarClient db, string[] whereColumns, string[] updateColumns) where T : class, new()
        {
            return db.Fastest<T>().AS(TableName).BulkUpdate(t, whereColumns, updateColumns);
        }
        
        #region 删除缓存
        /// 
        /// 根据主键更新实体(为null字段不更新,注意model有默认值的情况)并删除缓存,返回影响条数(实体字段要有主键特性)
        /// 
        /// 
        /// 
        /// 
        public int UpdateModelByKey_RemoveDataCache<T>(T t) where T : class, new()
        {
            return UpdateModelByKey_RemoveDataCache(t, SqlsugarHelper.Instance);
        }

        /// 
        /// 根据主键更新实体,返回影响条数(实体字段要有主键特性)并删除缓存,返回影响条数(实体字段要有主键特性)
        /// 
        /// 
        /// 
        /// (事务的db对象)
        /// 
        public int UpdateModelByKey_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
        {
            //字段null,不进行更新
            return db.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true).RemoveDataCache().ExecuteCommand();
        }


        /// 
        /// 根据条件表达式更新实体(指定要更新的列)并删除缓存,返回影响条数
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public int UpdateModels_RemoveDataCache<T>(T t, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
        {
            return UpdateModels_RemoveDataCache<T>(t, columns, expressionWhere, Instance);
        }

        /// 
        /// 根据条件表达式更新实体(指定要更新的列)并删除缓存,返回影响条数
        /// 
        /// 
        /// 
        /// 
        /// 条件表达式
        /// (事务的db对象)
        /// 
        public int UpdateModels_RemoveDataCache<T>(T t, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
        {
            return db.Updateable(t).UpdateColumns(columns).Where(expressionWhere).RemoveDataCache().ExecuteCommand();
        }

        /// 
        /// 动态更新,并删除缓存
        /// 
        /// 
        /// 写入要更新的字段
        /// where条件表达式
        /// 
        public int Update_RemoveDataCache<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
        {
            return Update_RemoveDataCache<T>(columns, expressionWhere, SqlsugarHelper.Instance);
            /* 调用示例
            Update(p => new Entity.SysAdmin { photo = photo, Password = newPwd }
               ,p => p.ID == sm.id && p.Password == oldPwd) > 0;
            */
        }

        /// 
        /// 动态更新,并删除缓存
        /// 
        /// 
        /// 要更新的字段
        /// where条件表达式
        /// 
        /// 
        public int Update_RemoveDataCache<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
        {
            return db.Updateable<T>().SetColumns(columns).
                //IgnoreColumns(ignoreAllNullColumns: true).//不能加此方法,会有“CommandText 属性尚未初始化”异常
                Where(expressionWhere).RemoveDataCache().ExecuteCommand();
            /* 调用示例
             Update(p => new Entity.SysAdmin { photo = photo, Password = newPwd }
                ,p => p.ID == sm.id && p.Password == oldPwd ,db) > 0;
             */
        }

        #endregion

        #endregion

        #region 删除方法

        /// 
        /// 删除ids集合条件的字符串(高效率写法,注意防止注入攻击)
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// 主键字段
        /// 
        public static bool DeleteByWhereSql_ids<T>(string ids, string key = "id") where T : class, new()
        {
            return DeleteByWhereSql_ids<T>(ids, SqlsugarHelper.Instance, key);
        }

        /// 
        /// 删除ids集合条件的字符串(高效率写法,注意防止注入攻击)
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// (事务的db对象)
        /// 主键字段
        /// 
        public static bool DeleteByWhereSql_ids<T>(string ids, SqlSugarClient db, string key = "id") where T : class, new()
        {
            return db.Deleteable<T>().Where(string.Format(" {0} IN ({1})", key, ids)).ExecuteCommand() > 0;
        }

        /// 
        /// 删除ids集合条件的字符串
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式 
        /// 
        public static bool DeleteByIds<T>(string ids) where T : class, new()
        {
            return DeleteByIds<T>(ids, SqlsugarHelper.Instance);
        }

        /// 
        /// 删除ids集合条件的字符串
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式 
        /// (事务的db对象)
        /// 
        public static bool DeleteByIds<T>(string ids, SqlSugarClient db) where T : class, new()
        {
            return db.Deleteable<T>(GetIntListByString(ids)).ExecuteCommand() > 0;
        }

        /// 
        /// 删除ids集合条件的字符串
        /// 
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// 
        public static bool DeleteByInt64_Ids<T>(string ids) where T : class, new()
        {
            return DeleteByInt64_Ids<T>(ids, SqlsugarHelper.Instance);
        }

        /// 
        /// 删除ids集合条件的字符串
        /// 
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// (事务的db对象)
        /// 
        public static bool DeleteByInt64_Ids<T>(string ids, SqlSugarClient db) where T : class, new()
        {
            return db.Deleteable<T>(GetLongListByString(ids)).ExecuteCommand() > 0;
        }

        /// 
        /// 删除数据
        /// 
        /// 
        /// 
        /// 表名称
        /// 条件表达式
        /// 
        public int Deleteable<T>(string TableName, Expression<Func<T, bool>> expression) where T : class, new()
        {
            return Deleteable( TableName, expression, SqlsugarHelper.Instance);
        }


        /// 
        /// 根据条件表达式删除,返回影响条数
        /// 
        /// 
        /// 表达式
        /// (事务的db对象)
        /// 
        public static int Deleteable<T>(string TableName,Expression<Func<T, bool>> expression, SqlSugarClient db) where T : class, new()
        {
            return db.Deleteable<T>().AS(TableName).Where(expression).ExecuteCommand();
        }

        #region 删除缓存

        /// 
        /// 删除ids集合条件的字符串(高效率写法,注意防止注入攻击),并删除缓存
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// 主键字段
        /// 
        public static bool DeleteByWhereSql_ids_RemoveDataCache<T>(string ids, string key = "id") where T : class, new()
        {
            return DeleteByWhereSql_ids_RemoveDataCache<T>(ids, SqlsugarHelper.Instance, key);
        }

        /// 
        /// 删除ids集合条件的字符串(高效率写法,注意防止注入攻击),并删除缓存
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// (事务的db对象)
        /// 主键字段
        /// 
        public static bool DeleteByWhereSql_ids_RemoveDataCache<T>(string ids, SqlSugarClient db, string key = "id") where T : class, new()
        {
            return db.Deleteable<T>().Where(string.Format(" {0} IN ({1})", key, ids)).RemoveDataCache().ExecuteCommand() > 0;
        }


        /// 
        /// 删除ids集合条件的字符串,并删除缓存
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式 
        /// 
        public static bool DeleteByIds_RemoveDataCache<T>(string ids) where T : class, new()
        {
            return DeleteByIds_RemoveDataCache<T>(ids, Instance);
        }

        /// 
        /// 删除ids集合条件的字符串,并删除缓存
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式 
        /// (事务的db对象)
        /// 
        public static bool DeleteByIds_RemoveDataCache<T>(string ids, SqlSugarClient db) where T : class, new()
        {
            return db.Deleteable<T>(GetIntListByString(ids)).RemoveDataCache().ExecuteCommand() > 0;
        }

        /// 
        /// 删除ids集合条件的字符串,并删除缓存
        /// 
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// 
        public static bool DeleteByInt64_Ids_RemoveDataCache<T>(string ids) where T : class, new()
        {
            return DeleteByInt64_Ids_RemoveDataCache<T>(ids, Instance);
        }

        /// 
        /// 删除ids集合条件的字符串,并删除缓存
        /// 
        /// 
        /// ids为字符串 "1,2,3"或"1" 形式
        /// (事务的db对象)
        /// 
        public static bool DeleteByInt64_Ids_RemoveDataCache<T>(string ids, SqlSugarClient db) where T : class, new()
        {
            return db.Deleteable<T>(GetLongListByString(ids)).RemoveDataCache().ExecuteCommand() > 0;
        }

        #endregion

        #endregion

        #region ids转集合

        /// 
        /// 将字符串转成int数组(, 号分割)
        /// 
        /// 
        /// 
        public static int[] GetIntListByString(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids)) return null;
            return Array.ConvertAll<string, int>(ids.Split(','), Int32.Parse);
        }

        /// 
        /// 将字符串转成long数组(, 号分割)
        /// 
        /// 
        /// 
        public static long[] GetLongListByString(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids)) return null;
            return Array.ConvertAll<string, long>(ids.Split(','), Int64.Parse);
        }

        #endregion

        #region 扩展查询,不建议使用
        /// 
        /// 简单查询数据
        /// 
        /// 表名
        /// 字段
        /// 条件
        /// 
        public DataTable GetDataTable(string tableName, string columns, Dictionary<string, object> dicWhere)
        {
            var db = SqlsugarHelper.Instance;
            string sql = string.Format("select {0} from {1} ", columns, tableName);

            List<SugarParameter> sqlParams = new List<SugarParameter>();

            if (dicWhere != null)
            {
                string whereSql = dicFill_where(dicWhere, ref sqlParams);

                return db.Ado.GetDataTable(sql + " where 1=1 " + whereSql, sqlParams.ToArray());
            }
            else
            {
                return db.Ado.GetDataTable(sql);
            }
        }

        /// 
        /// 查询数据
        /// 
        /// sql
        /// 条件
        /// where 条件,加and (注意sql注入攻击)
        /// 扩展参数
        /// 
        public DataTable GetDataTableBySql(string sqlStr, Dictionary<string, object> dicWhere, string whereSql = "", List<SugarParameter> parList = null)
        {
            var db = SqlsugarHelper.Instance;
            List<SugarParameter> sqlParams = new List<SugarParameter>();

            string _whereSql = dicFill_where(dicWhere, ref sqlParams) + whereSql;

            if (parList != null && parList.Count > 0)
            {
                sqlParams.AddRange(parList);
            }

            if (sqlParams.Count > 0)
            {
                return db.Ado.GetDataTable(string.Format(sqlStr + " {0} ", " where 1=1 " + _whereSql), sqlParams.ToArray());
            }
            else
            {
                return db.Ado.GetDataTable(string.IsNullOrEmpty(whereSql) ? sqlStr : sqlStr + whereSql);
            }
        }

        /// 
        /// 查询数据
        /// 
        /// sql语句
        /// 参数
        /// 连接字符串
        /// 数据库类型
        /// Datatable
        public DataTable Query(string sql, List<SugarParameter> parameters)
        {
            var dt = SqlsugarHelper.Instance.Ado.GetDataTable(sql, parameters);
            return dt;
        }
        /// 
        /// 分页取数据
        /// 
        /// 前台子查询生成表名字
        /// where条件字段集合
        /// where条件,加 and (注意sql注入)
        /// 排序字段
        /// 当前页码(从0开始)
        /// 一页显示多少条记录
        /// 返回总记录
        /// cte的sql
        /// 
        public DataTable GetDataPage(string tableName, Dictionary<string, object> dicWhere, string whereSql, string orderbyColumn, int pageIndex, int pageSize, out int recordCount, string cte = "")
        {
            var db = SqlsugarHelper.Instance;
            List<SugarParameter> par = new List<SugarParameter>();

            StringBuilder where = new StringBuilder();
            where.Append(" where 1=1 ");
            where.Append(dicFill_where(dicWhere, ref par) + whereSql);


            string tableSql = tableName.Contains("select ") ?
                string.Format(" ( " + tableName + " {0} ) pageTable ", where.ToString()) :
                string.Format(" ( select * from " + tableName + " {0} ) pageTable ", where.ToString());

            string sql = string.Format(@"{5} 
                       select  {0},row_number() over(order by {1}) rid into #tt from {2} 
                               Order By {1}  select * from  #tt where rid> {3} and rid<={4} ;select count(1) from #tt ;drop table  #tt ",

                " * ", orderbyColumn, tableSql, pageSize * pageIndex, pageSize * (pageIndex + 1), cte);


            DataSet ds = par.Count > 0 ? db.Ado.GetDataSetAll(sql, par.ToArray()) : db.Ado.GetDataSetAll(sql);

            recordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString());

            return ds.Tables[0];
        }

        /// 
        /// 封装where参数sql语句
        /// 
        /// 
        /// 
        /// 
        private string dicFill_where(Dictionary<string, object> dicWhere, ref List<SugarParameter> par)
        {
            StringBuilder whereSql = new StringBuilder();

            if (dicWhere != null && dicWhere.Count > 0)
            {
                
                string keyName;
                foreach (KeyValuePair<string, object> keyDic in dicWhere)
                {
                    keyName = getParameterName(keyDic.Key);
                    if (keyDic.Value.ToString().Contains("%") ||
                        keyDic.Value.ToString().Contains("_") ||
                        (keyDic.Value.ToString().Contains("[") && keyDic.Value.ToString().Contains("]"))
                    ) //只要是含有 % _  [ ]  都是按照模糊查询
                    {
                        whereSql.AppendFormat(" and {0} like @{1} ", keyDic.Key, keyName);
                    }
                    else if (keyDic.Value.ToString().Contains("|"))
                    {
                        whereSql.AppendFormat(" Or {0} = @{1} ", keyDic.Key, keyName);
                    }
                    else
                    {
                        whereSql.AppendFormat(" and {0} = @{1} ", keyDic.Key, keyName);
                    }

                    par.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
                }
            }
            return whereSql.ToString();
        }

        /// 
        /// 把字段名称 [dbo].[new].[title] ,取字段名title
        /// 
        /// 字段
        /// 
        private string getParameterName(string key)
        {
            var temp = key.Split('.');
            StringBuilder sb = new StringBuilder(temp[temp.Length - 1]);
            sb.Replace("[", string.Empty).Replace("]", string.Empty);
            sb.Replace("|", string.Empty);
            return sb.ToString();
        }

        /// 
        /// 动态添加数据
        /// 
        /// 表名
        /// 参数和对应值集合
        /// 新添加数据id
        public int InsertDB(string tableName, Dictionary<string, object> dic)
        {
            StringBuilder columns = new StringBuilder();
            StringBuilder columnParameters = new StringBuilder();
            List<SugarParameter> sqlParams = new List<SugarParameter>();
            if (dic.Count > 0)
            {
                foreach (KeyValuePair<string, object> keyDic in dic)
                {
                    columns.AppendFormat(",{0}", keyDic.Key);
                    columnParameters.AppendFormat(",@{0}", getParameterName(keyDic.Key));
                    sqlParams.Add(new SugarParameter(string.Format("@{0}", getParameterName(keyDic.Key)), keyDic.Value));
                }
            }
            else
            {
                return 0;
            }

            string sql =
                string.Format("insert into {0}({1}) values ({2});select @@IDENTITY",
                    tableName, columns.ToString().Substring(1), columnParameters.ToString().Substring(1));

            return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams.ToArray());
        }

        /// 
        /// 动态更新数据
        /// 
        /// 表名
        /// 参数和对应值集合
        /// where 条件(注意sql注入攻击)
        /// 是否更新成功!
        public bool UpdateDB(string tableName, Dictionary<string, object> dic, string whereSql)
        {
            StringBuilder columns = new StringBuilder();

            List<SugarParameter> sqlParams = new List<SugarParameter>();
            string keyName;
            if (dic != null && dic.Count > 0)
            {
                foreach (KeyValuePair<string, object> keyDic in dic)
                {
                    keyName = getParameterName(keyDic.Key);
                    columns.AppendFormat(",{0}=@{1}", keyDic.Key, keyName);
                    sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
                }
            }
            else
            {
                return false;
            }


            string sql =
                string.Format("update {0} set {1} where {2}",
                    tableName, columns.ToString().Substring(1), whereSql);

            return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams) > 0;
        }


        /// 
        /// 动态更新数据
        /// 
        /// 表名
        /// 参数和对应值集合
        /// where条件参数和对应值集合
        /// 是否更新成功!
        public bool UpdateDB(string tableName, Dictionary<string, object> dic, Dictionary<string, object> dicWhere)
        {
            StringBuilder columns = new StringBuilder();
            StringBuilder wheresSql = new StringBuilder();
            List<SugarParameter> sqlParams = new List<SugarParameter>();
            string keyName;
            if (dic != null && dic.Count > 0)
            {
                foreach (KeyValuePair<string, object> keyDic in dic)
                {
                    keyName = getParameterName(keyDic.Key);
                    columns.AppendFormat(",{0}=@{1}", keyDic.Key, keyName);
                    sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
                }
            }
            else
            {
                return false;
            }

            if (dicWhere != null && dicWhere.Count > 0)
            {
                foreach (KeyValuePair<string, object> keyDic in dicWhere)
                {
                    keyName = getParameterName(keyDic.Key);
                    wheresSql.AppendFormat(" and {0}=@{1}", keyDic.Key, keyName);
                    sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
                }
            }
            else
            {
                return false;
            }

            string sql =
                string.Format("update {0} set {1} where 1=1 {2}",
                    tableName, columns.ToString().Substring(1), wheresSql.ToString().Substring(1));

            return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams) > 0;
        }


        /// 
        /// 查询是否存在此记录
        /// 
        /// 表名
        /// 条件
        /// 自定义条件
        /// 
        public bool Exists(string tableName, Dictionary<string, object> dicWhere, string whereSql = "")
        {
            string sql = string.Format("select count(1) from {0} where 1=1 ", tableName);

            List<SugarParameter> sqlParams = new List<SugarParameter>();

            string whereSql2 = dicFill_where(dicWhere, ref sqlParams) + whereSql;

            return SqlsugarHelper.Instance.Ado.GetInt(sql + whereSql2, sqlParams) > 0;
        }

        #endregion


     

    }
    #region 动态拼接lambda表达式

    /// 
    /// Lambda表达式拼接扩展类
    /// 
    public static class Utility
    {
        /// 
        /// Lambda表达式拼接
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // 构建参数映射(从第二个参数到第一个参数)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
            // 将第二个lambda表达式中的参数替换为第一个lambda表达式的参数
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            // 将lambda表达式体的组合应用于第一个表达式中的参数
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }
        /// 
        /// and扩展
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.AndAlso);
        }
        /// 
        /// or扩展
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.OrElse);
        }
    }
    /// 
    /// 
    /// 
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;
        /// 
        /// 
        /// 
        /// 
        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }
    }
    #endregion

你可能感兴趣的:(C#,数据库,sql,c#)