using JinYuan.DAL; using JinYuan.DAL.Enums; using JinYuan.DAL.Models; using Org.BouncyCastle.Asn1; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Linq.Expressions; using System.Runtime.Remoting.Contexts; using System.Text; using System.Threading.Tasks; namespace JinYuan.DAL { public class SQLSugarService : ISugarHepler { public void SetConnectionStr(string connectionStr, SqlSugar.DbType dbType= SqlSugar.DbType.SqlServer) { SQLSugarHelper.connString = connectionStr; SqlSugarDb = SQLSugarHelper.SqlSugarClient; } /// /// 数据库连接对象 /// public SqlSugarScope SqlSugarDb { get; set; } #region 数据库管理 /// /// 添加列 /// /// 表名 /// 列信息 /// 值 public bool AddColumn(string tableName, DbColumnInfo column) { return SqlSugarDb.DbMaintenance.AddColumn(tableName, column); } /// /// 添加主键 /// /// 表名 /// 列名 /// 值 public bool AddPrimaryKey(string tableName, string columnName) { return SqlSugarDb.DbMaintenance.AddPrimaryKey(tableName, columnName); } /// /// 备份数据库 /// /// 数据库名 /// 文件名 /// 值 public bool BackupDataBase(string databaseName, string fullFileName) { return SqlSugarDb.DbMaintenance.BackupDataBase(databaseName, fullFileName); } /// /// 备份表 /// /// 旧表名 /// 行表名 /// 行数 /// 值 public bool BackupTable(string oldTableName, string newTableName, int maxBackupDataRows = int.MaxValue) { return SqlSugarDb.DbMaintenance.BackupTable(oldTableName, newTableName, maxBackupDataRows); } /// /// 创建表 /// /// 表名 /// 列集合 /// 是否创建主键 /// 值 public bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) { return SqlSugarDb.DbMaintenance.CreateTable(tableName, columns, isCreatePrimaryKey); } /// /// 删除列 /// /// 表名 /// 列名 /// 值 public bool DropColumn(string tableName, string columnName) { return SqlSugarDb.DbMaintenance.DropColumn(tableName, columnName); } /// /// 删除约束 /// /// 表名 /// 约束名 /// 值 public bool DropConstraint(string tableName, string constraintName) { return SqlSugarDb.DbMaintenance.DropConstraint(tableName, constraintName); } /// /// 删除表 /// /// /// 值 public bool DropTable(string tableName) { return SqlSugarDb.DbMaintenance.DropTable(tableName); } /// /// 获取列信息 /// /// 表名 /// 是否缓存 /// 值 public List GetColumnInfosByTableName(string tableName, bool isCache = true) { return SqlSugarDb.DbMaintenance.GetColumnInfosByTableName(tableName, isCache); } /// /// 获取自增列 /// /// 表名 /// 值 public List GetIsIdentities(string tableName) { return SqlSugarDb.DbMaintenance.GetIsIdentities(tableName); } /// /// 获取主键 /// /// 表名 /// 值 public List GetPrimaries(string tableName) { return SqlSugarDb.DbMaintenance.GetPrimaries(tableName); } /// /// 获取表集合 /// /// 是否缓存 /// 值 public List GetTableInfoList(bool isCache = true) { return SqlSugarDb.DbMaintenance.GetTableInfoList(isCache); } /// /// 获取视图集合 /// /// 是否缓存 /// 值 public List GetViewInfoList(bool isCache = true) { return SqlSugarDb.DbMaintenance.GetViewInfoList(isCache); } /// /// 检测列是否存在 /// /// 表名 /// 列名 /// 值 public bool IsAnyColumn(string tableName, string column) { return SqlSugarDb.DbMaintenance.IsAnyColumn(tableName, column); } /// /// 检测约束 /// /// 约束名称 /// 值 public bool IsAnyConstraint(string constraintName) { return SqlSugarDb.DbMaintenance.IsAnyConstraint(constraintName); } /// /// 检测是否有任何系统表权限 /// /// 值 public bool IsAnySystemTablePermissions() { return SqlSugarDb.DbMaintenance.IsAnySystemTablePermissions(); } /// /// 检测表是否存在 /// /// 表名 /// 是否缓存 /// 值 public bool IsAnyTable(string tableName, bool isCache = true) { return SqlSugarDb.DbMaintenance.IsAnyTable(tableName, isCache); } /// /// 检测列是否自增列 /// /// 表名 /// 列名 /// 值 public bool IsIdentity(string tableName, string column) { return SqlSugarDb.DbMaintenance.IsIdentity(tableName, column); } /// /// 检测列是否主键 /// /// 表名 /// 列名 /// 值 public bool IsPrimaryKey(string tableName, string column) { return SqlSugarDb.DbMaintenance.IsPrimaryKey(tableName, column); } /// /// 重置列名 /// /// 表名 /// 旧列名 /// 新列名 /// 值 public bool RenameColumn(string tableName, string oldColumnName, string newColumnName) { return SqlSugarDb.DbMaintenance.RenameColumn(tableName, oldColumnName, newColumnName); } /// /// 重置表数据 /// /// 表名 /// 值 public bool TruncateTable(string tableName) { return SqlSugarDb.DbMaintenance.TruncateTable(tableName); } /// /// 修改列信息 /// /// 表名 /// 列信息 /// 值 public bool UpdateColumn(string tableName, DbColumnInfo column) { return SqlSugarDb.DbMaintenance.UpdateColumn(tableName, column); } /// /// 获取数据库时间 /// /// 返回值 public DateTime GetDataBaseTime() { return SqlSugarDb.GetDate(); } #endregion #region 查询 /// /// 查询所有 /// /// /// /// public List QueryAll() where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.UpdLock); return up.ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询-返回自定义数据 /// /// 泛型参数(集合成员的类型) /// 返回值类型 /// 返回值表达式 /// 查询表达式 /// 值 public TResult QuerySelect(Expression> expression, Expression> whereLambda = null) where T : class, new() { try { var datas = SqlSugarDb.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).First(); return datas; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询-返回自定义数据 /// /// 泛型参数(集合成员的类型) /// 返回值类型 /// 返回值表达式 /// 查询表达式 /// 值 public List QuerySelectList(Expression> expression, Expression> whereLambda = null) where T : class, new() { try { var datas = SqlSugarDb.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).ToList(); return datas; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询单条数据 /// /// 泛型参数(集合成员的类型) /// 查询表达式 /// 值 public T Query(Expression> whereLambda = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda != null) { up = up.Where(whereLambda); } return up.First(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 异步查询单条数据 /// /// 泛型参数(集合成员的类型) /// 查询表达式 /// /// public Task QueryAsync(Expression> whereLambda = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda != null) { up = up.Where(whereLambda); } return up.FirstAsync(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 根据条件查询排序数据 /// /// /// /// /// public T Query(Expression> whereLambda2 = null, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda2 != null) { up = up.Where(whereLambda2); } if (whereLambda != null) { up = up.OrderBy(whereLambda, byType); } return up.First(); } catch (Exception ex) { throw new Exception(ex.Message); } } public T Query(QueryDescriptor query = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (query != null) { if (query.Conditions != null) { var conds = ParseCondition(query.Conditions); up = up.Where(conds); } if (query.OrderBys != null) { var orderBys = ParseOrderBy(query.OrderBys); up = up.OrderBy(orderBys); } } return up.First(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询集合 /// /// 泛型参数(集合成员的类型) /// 过滤条件 /// 实体 public List QueryWhereList(Expression> whereLambda = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.UpdLock); if (whereLambda != null) { up = up.Where(whereLambda); } return up.ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询集合 /// /// 泛型参数(集合成员的类型) /// 过滤条件 /// 实体 public List QueryList(QueryDescriptor query = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (query != null) { if (query.Conditions != null) { var conds = ParseCondition(query.Conditions); up = up.Where(conds); } if (query.OrderBys != null) { var orderBys = ParseOrderBy(query.OrderBys); up = up.OrderBy(orderBys); } } return up.ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询前N条数据 /// /// /// /// /// /// /// public List QueryList(string sort, int Take, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda != null) { up = up.Where(whereLambda); } if (sort != "") { var orderBys = ParseOrderBy(sort, byType); up = up.OrderBy(orderBys).Take(Take); } return up.ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 根据字段查询排列 /// /// /// /// /// /// public List QueryList(string sort, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda != null) { up = up.Where(whereLambda); } if (sort != "") { var orderBys = ParseOrderBy(sort, byType); up = up.OrderBy(orderBys); } return up.ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 排序转换 /// /// /// /// private string ParseOrderBy(string sort, OrderByType order) { var conds = ""; switch (order) { case OrderByType.Asc: conds += $"{sort} asc,"; break; case OrderByType.Desc: conds += $"{sort} desc,"; break; default: throw new ArgumentOutOfRangeException(); } return conds.TrimEnd(','); } /// /// 查询集合 /// /// 泛型参数(集合成员的类型) /// sql /// 实体 public List QuerySqlList(string sql) where T : class, new() { try { return SqlSugarDb.SqlQueryable(sql).ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 分页查询 /// /// 泛型参数(集合成员的类型) /// 过滤条件 /// 总行数 /// 实体 public List QueryPageList(QueryDescriptor query, out int totalCount) where T : class, new() { if (query == null) { throw new ArgumentNullException(nameof(query)); } var listDatas = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (query.Conditions != null) { var conds = ParseCondition(query.Conditions); listDatas = listDatas.Where(conds); } if (query.OrderBys != null) { var orderBys = ParseOrderBy(query.OrderBys); listDatas = listDatas.OrderBy(orderBys); } totalCount = 0; if (query.PageSize == 0) { var datas = listDatas.ToList(); totalCount = datas.Count; return datas; } else { var datas = listDatas.ToPageList(query.PageIndex, query.PageSize, ref totalCount); return datas; } } /// /// 查询集合-多值 /// /// 泛型参数(集合成员的类型) /// 字段名 /// 数据集合 /// 值 public List In(string inFieldName, List inValues) where T : class, new() { try { return SqlSugarDb.Queryable().With(SqlWith.NoLock).In(inFieldName, inValues).ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询集合-通过多值(主键) /// /// 泛型参数(集合成员的类型) /// 主键数据集合 /// 值 public List In(List values) where T : class, new() { return SqlSugarDb.Queryable().With(SqlWith.NoLock).In(values).ToList(); } /// /// 查询集合 /// /// 泛型参数(集合成员的类型) /// 查询表达式 /// 实体 public DataTable QueryDataTable(Expression> whereLambda = null) where T : class, new() { try { ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (whereLambda != null) { up = up.Where(whereLambda); } return up.ToDataTable(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询集合 /// /// sql /// 实体 public DataTable QueryDataTable(string sql) { try { return SqlSugarDb.Ado.GetDataTable(sql); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 查询单个值 /// /// sql /// 单个值 public object QuerySqlScalar(string sql) { try { return SqlSugarDb.Ado.GetScalar(sql); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 分页查询 /// /// 泛型参数(集合成员的类型) /// 过滤条件 /// 总行数 /// DataTable public DataTable QueryDataTablePageList(QueryDescriptor query, out int totalCount) where T : class, new() { if (query == null) { throw new ArgumentNullException(nameof(query)); } var listDatas = SqlSugarDb.Queryable().With(SqlWith.NoLock); if (query.Conditions != null) { var conds = ParseCondition(query.Conditions); listDatas = listDatas.Where(conds); } if (query.OrderBys != null) { var orderBys = ParseOrderBy(query.OrderBys); listDatas = listDatas.OrderBy(orderBys); } totalCount = 0; var datas = listDatas.ToDataTablePage(query.PageIndex, query.PageSize, ref totalCount); return datas; } #endregion #region 新增 /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 操作影响的行数 public int Add(T entity) where T : class, new() { try { var result = SqlSugarDb.Insertable(entity).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 泛型集合 /// 操作影响的行数 public int Add(List entitys) where T : class, new() { try { if (entitys.Count == 0) return 1; var result = SqlSugarDb.Insertable(entitys).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 字典集合(Key:列名 Value:值) /// 操作影响的行数 public int Add(Dictionary keyValues) where T : class, new() { try { var result = SqlSugarDb.Insertable(keyValues).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 返回实体 public T AddReturnEntity(T entity) where T : class, new() { try { var result = SqlSugarDb.Insertable(entity).ExecuteReturnEntity(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 返回自增列 public int AddReturnIdentity(T entity) where T : class, new() { try { var result = SqlSugarDb.Insertable(entity).ExecuteReturnIdentity(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 返回bool public bool AddReturnBool(T entity) where T : class, new() { try { var result = SqlSugarDb.Insertable(entity).With(SqlWith.UpdLock).ExecuteCommand() > 0; return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 新增 /// /// 泛型参数(集合成员的类型) /// 泛型集合 /// 返回bool public bool AddReturnBool(List entitys) where T : class, new() { try { if (entitys.Count == 0) return true; var result = SqlSugarDb.Insertable(entitys).ExecuteCommand() > 0; return result; } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion #region 修改 /// /// 修改(主键是更新条件) /// /// 泛型参数(集合成员的类型) /// 实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 /// 不更新的列 /// 是否加锁 /// 操作影响的行数 /// public int Update(T entity, List lstIgnoreColumns = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { up = up.IgnoreColumns(false); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改(主键是更新条件) /// /// 泛型参数(集合成员的类型) /// 实体对象集合(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 /// 不更新的列 /// 是否加锁 /// 操作影响的行数 public int Update(List entitys, List lstIgnoreColumns = null, bool isLock = true) where T : class, new() { try { if (entitys.Count == 0) return 1; IUpdateable up = SqlSugarDb.Updateable(entitys); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First())); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 条件 /// 不更新的列 /// 是否加锁 /// 操作影响的行数 public int Update(T entity, Expression> where, List lstIgnoreColumns = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First())); } up = up.Where(where); if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 条件 /// 是否加锁 /// 操作影响的行数 public int Update(Expression> update, Expression> where = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable().UpdateColumns(update); if (where != null) { up = up.Where(where); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改加1 /// /// /// /// /// /// public int Update(Expression> update, Expression> where = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable().SetColumns(update); if (where != null) { up = up.Where(where); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改单条数据 /// /// /// 实体类 /// 指定更新行 /// 更新表达式 /// 是否加锁 /// /// public int UpdateSingle(T entity, Expression> IgnoreColumns = null, Expression> where = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable(entity); if (IgnoreColumns != null) { up.UpdateColumns(IgnoreColumns); } if (where != null) { up.Where(where); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; //SqlSugarDb.Updateable(new T () //{ // Id = entity.Id, // EmailArr = "test@test.com", // EmailContent = "测试邮件,请忽略111" //}).UpdateColumns(it => new { it.EmailArr, it.EmailContent }).ExecuteCommandAsync(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改 /// /// 泛型参数(集合成员的类型) /// 字典集合(Key:列名 Value:值) /// 条件 /// 是否加锁 /// 操作影响的行数 public int Update(Dictionary keyValues, Expression> where = null, bool isLock = true) where T : class, new() { try { IUpdateable up = SqlSugarDb.Updateable(keyValues); if (where != null) { up = up.Where(where); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 批量修改需要更新的列 /// /// 泛型参数(集合成员的类型) /// 实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 /// 更新指定列 /// 条件(为空则以主键更新,反之需要把wherecolumns中的列加到UpdateColumns中) /// 是否加锁 /// 操作影响的行数 public int UpdateColumns(List entitys, Expression> updateColumns, Expression> wherecolumns = null, bool isLock = true) where T : class, new() { try { if (entitys.Count == 0) return 1; IUpdateable up = SqlSugarDb.Updateable(entitys).UpdateColumns(updateColumns); if (wherecolumns != null) { up = up.WhereColumns(wherecolumns); } if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 修改 通过RowVer及主键Code 更新 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 不更新的列 /// 是否加锁 /// 操作影响的行数 public int UpdateRowVer(T entity, List lstIgnoreColumns = null, bool isLock = true) where T : class, new() { try { Type ts = entity.GetType(); var rowVerProperty = ts.GetProperty("RowVer"); if (rowVerProperty == null) { throw new Exception("Column RowVer Not Exist"); } if (rowVerProperty.GetValue(entity, null) == null) { throw new Exception("RowVer Value Is Null"); } var codeProperty = ts.GetProperty("Code"); if (codeProperty == null) { throw new Exception("Column Code Not Exist"); } if (codeProperty.GetValue(entity, null) == null) { throw new Exception("Code Value Is Null"); } var rowVerValue = int.Parse(rowVerProperty.GetValue(entity, null).ToString()); var codeValue = codeProperty.GetValue(entity, null).ToString(); var sqlWhere = $" RowVer={rowVerValue} AND Code='{codeValue}'"; rowVerProperty.SetValue(entity, rowVerValue + 1, null); IUpdateable up = SqlSugarDb.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First())); } up = up.Where(sqlWhere); if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } //表达式写2列更新2列,其他不会更新 /// /// 修改 /// /// 泛型参数(集合成员的类型) /// 实体对象 /// 更新条件 /// 是否加锁 /// 操作影响的行数 public int UpdateRowVer(Expression> update, Dictionary where, bool isLock = true) where T : class, new() { try { if (!where.ContainsKey("RowVer")) { throw new Exception("Column RowVer Not Exist"); } if (where["RowVer"] == null) { throw new Exception("RowVer Value Is Null"); } if (update.Body.ToString().IndexOf("RowVer", StringComparison.Ordinal) == -1) { throw new Exception("Column RowVer Update Is Null"); } var sqlWhere = ""; foreach (var item in where) { sqlWhere += string.IsNullOrWhiteSpace(sqlWhere) ? $" {item.Key}='{item.Value}'" : $" and {item.Key}='{item.Value}'"; } IUpdateable up = SqlSugarDb.Updateable().UpdateColumns(update).Where(sqlWhere); if (isLock) { up = up.With(SqlWith.UpdLock); } var result = up.ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion #region 删除 /// /// 初始化表 /// /// /// public void Delete() where T : class, new() { try { SqlSugarDb.DbMaintenance.TruncateTable(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 删除 /// /// 泛型参数(集合成员的类型) /// 主键值 /// 是否加锁 /// 操作影响的行数 public int DeleteByPrimary(List primaryKeyValues, bool isLock = true) where T : class, new() { try { var result = isLock ? SqlSugarDb.Deleteable().In(primaryKeyValues).With(SqlWith.RowLock).ExecuteCommand() : SqlSugarDb.Deleteable().In(primaryKeyValues).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 删除 /// /// 泛型参数(集合成员的类型) /// 实体对象 (必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 /// 是否加锁 /// 操作影响的行数 public int Delete(T entity, bool isLock = true) where T : class, new() { try { var result = isLock ? SqlSugarDb.Deleteable(entity).With(SqlWith.RowLock).ExecuteCommand() : SqlSugarDb.Deleteable(entity).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 删除 /// /// 泛型参数(集合成员的类型) /// 实体对象 (必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 /// 是否加锁 /// 操作影响的行数 public int Delete(List entity, bool isLock = true) where T : class, new() { try { var result = isLock ? SqlSugarDb.Deleteable(entity).With(SqlWith.RowLock).ExecuteCommand() : SqlSugarDb.Deleteable(entity).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 删除 /// /// 泛型参数(集合成员的类型) /// 条件 /// 是否加锁 /// 操作影响的行数 public int Delete(Expression> where, bool isLock = true) where T : class, new() { try { var result = isLock ? SqlSugarDb.Deleteable().Where(where).With(SqlWith.RowLock).ExecuteCommand() : SqlSugarDb.Deleteable().Where(where).ExecuteCommand(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 通过多值(主键)删除数据集 /// /// 泛型参数(集合成员的类型) /// 数据集合 /// 值 public int DeleteIn(List inValues) where T : class, new() { return SqlSugarDb.Deleteable().With(SqlWith.RowLock).In(inValues).ExecuteCommand(); } #endregion #region 私有方法 /// /// SqlParameter转换SugarParameter /// /// 参数 /// private List ConvetParameter(List parameters) { var listParams = new List(); foreach (var p in parameters) { var par = new SugarParameter(p.ParameterName, p.Value) { DbType = p.DbType, Direction = p.Direction }; if (!string.IsNullOrWhiteSpace(p.TypeName)) { par.TypeName = p.TypeName; } listParams.Add(par); } return listParams; } /// /// 过滤条件转换 /// /// 过滤条件 /// 值 private List ParseCondition(List contitons) { var conds = new List(); contitons.Insert(0, new QueryCondition { Operator = QueryOperator.Equal, Key = "1", Value = "1" }); #region Or条件组装 var orConditional = new ConditionalCollections { ConditionalList = new List>() }; foreach (var con in contitons.Where(m => m.Character == QueryCharacter.Or)) { if (orConditional.ConditionalList.Count == 0) { var cond = new KeyValuePair (WhereType.And, new ConditionalModel() { FieldName = con.Key, ConditionalType = (ConditionalType)(int)con.Operator, FieldValue = con.Value.ToString() }); orConditional.ConditionalList.Add(cond); } else { var cond = new KeyValuePair (WhereType.Or, new ConditionalModel() { FieldName = con.Key, ConditionalType = (ConditionalType)(int)con.Operator, FieldValue = con.Value.ToString() }); orConditional.ConditionalList.Add(cond); } } #endregion #region And条件组装 foreach (var con in contitons.Where(m => m.Character == QueryCharacter.And)) { if (con.Key.Contains(",")) { ParseKeyOr(con, orConditional); } else if (con.Operator == QueryOperator.DateRange) { conds.AddRange(ParseRange(con, con.Operator)); } else { conds.Add(new ConditionalModel() { FieldName = con.Key, ConditionalType = (ConditionalType)(int)con.Operator, FieldValue = con.Value.ToString() }); } } #endregion //Or条件是否存在 if (orConditional.ConditionalList.Count > 0) { conds.Add(orConditional); } return conds; } /// /// Key逗号隔开转换Or条件 /// /// 过滤条件 /// 条件集合 /// 值 private void ParseKeyOr(QueryCondition condition, ConditionalCollections conditionalCollections) { var objectKeys = condition.Key.Split(','); foreach (var objKey in objectKeys) { if (conditionalCollections.ConditionalList.Count == 0) { var cond = new KeyValuePair (WhereType.And, new ConditionalModel() { FieldName = objKey, ConditionalType = (ConditionalType)(int)condition.Operator, FieldValue = condition.Value.ToString() }); conditionalCollections.ConditionalList.Add(cond); } else { var cond = new KeyValuePair (WhereType.Or, new ConditionalModel() { FieldName = objKey, ConditionalType = (ConditionalType)(int)condition.Operator, FieldValue = condition.Value.ToString() }); conditionalCollections.ConditionalList.Add(cond); } } } /// /// 转换区域 /// /// 过滤条件 /// 条件类型 /// 值 private List ParseRange(QueryCondition condition, QueryOperator queryOperator) { var objectValue = condition.Value.ToString().Split('|'); var conditionalList = new List(); if (objectValue.Length == 2) { var startValue = objectValue[0]; var endValue = objectValue[1]; if (queryOperator == QueryOperator.DateRange) { if (startValue.IndexOf(":", StringComparison.Ordinal) == -1) { startValue = startValue + " 00:00:00"; } if (endValue.IndexOf(":", StringComparison.Ordinal) == -1) { endValue = endValue + " 23:59:59"; } } if (!string.IsNullOrWhiteSpace(objectValue[0])) { conditionalList.Add(new ConditionalModel() { FieldName = condition.Key, ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = startValue }); } if (!string.IsNullOrWhiteSpace(objectValue[1])) { conditionalList.Add(new ConditionalModel() { FieldName = condition.Key, ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = endValue }); } } return conditionalList; } /// /// 排序转换 /// /// 排序 /// 值 private string ParseOrderBy(List orderBys) { var conds = ""; foreach (var con in orderBys) { switch (con.Order) { case OrderSequence.Asc: conds += $"{con.Sort} asc,"; break; case OrderSequence.Desc: conds += $"{con.Sort} desc,"; break; default: throw new ArgumentOutOfRangeException(); } } return conds.TrimEnd(','); } #endregion public void Dispose() { SqlSugarDb.Ado.Dispose(); SqlSugarDb.Dispose(); } } }