using SqlSugar; using System.Linq.Expressions; using WMS.BZModels; using WMS.BZServices; using WMS.BZSqlSugar; namespace WMS.BZSqlSugar { public class PTRepository : SimpleClient where T : BaseEntityModel, new() { public PTRepository() { var lists = Util.ConfigHelper.GetConnectionConfigs().Connections; var connection = lists.FirstOrDefault(o => o.ConfigId == "pt"); if (connection == null) { throw new Exception("DB 初始化错误。"); } Context = new SqlSugarScope(new ConnectionConfig() { DbType = (DbType)connection.DataBaseType, ConnectionString = connection.ConnectionString, IsAutoCloseConnection = connection.IsAutoCloseConn, }, db => { //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (sql, pars) => { string log = $"【PT SQL语句】{UtilMethods.GetSqlString((DbType)connection.DataBaseType, sql, pars)}\n"; if (sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(log); } else if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(log); } else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(log); } else { log = $"【PT SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n"; Console.WriteLine(log); } }; }); } private object GetParsValue(SugarParameter x) { if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String) { return "'" + x.Value + "'"; } return x.Value; } /// /// /// /// /// public override T InsertReturnEntity(T t) { //t = CheckId.InitId(t); return Context.Insertable(t).ExecuteReturnEntity(); } /// /// 该方法默认不更新AddWho,AddTime /// /// /// public bool UpdateEntity(T entity) { return Context.Updateable(entity).IgnoreColumns(new string[] { "AddWho", "AddTime" }).ExecuteCommand() > 0; } public bool UpdateModelColumns(Expression> Columns, Expression> WhereExpression) { return Update(Columns, WhereExpression); } public T GetModelByExpression(Expression> WhereExpression) { return GetSingle(WhereExpression); } //public ISugarQueryable Queryable() //{ // return Context.Queryable(); //} #region query public bool Any(Expression> expression) { return Context.Queryable().Where(expression).Any(); } public ISugarQueryable Queryable() { return Context.Queryable(); } public List SqlQueryToList(string sql, object obj = null) { return Context.Ado.SqlQuery(sql, obj); } /// /// 根据主值查询单条数据 /// /// 主键值 /// 泛型实体 public T GetId(object pkValue) { return Context.Queryable().InSingle(pkValue); } /// /// 根据条件查询分页数据 /// /// /// /// public PagedInfo GetPages(Expression> where, PagerInfo parm) { var source = Context.Queryable().Where(where); return source.ToPage(parm); } /// /// 分页获取数据 /// /// 条件表达式 /// /// /// /// public PagedInfo GetPages(Expression> where, PagerInfo parm, Expression> order, OrderByType orderEnum = OrderByType.Asc) { var source = Context .Queryable() .Where(where) .OrderByIF(orderEnum == OrderByType.Asc, order, OrderByType.Asc) .OrderByIF(orderEnum == OrderByType.Desc, order, OrderByType.Desc); return source.ToPage(parm); } public PagedInfo GetPages(Expression> where, PagerInfo parm, Expression> order, string orderByType) { return GetPages(where, parm, order, orderByType == "desc" ? OrderByType.Desc : OrderByType.Asc); } /// /// 查询所有数据(无分页,请慎用) /// /// public List GetAll(bool useCache = false, int cacheSecond = 3600) { return Context.Queryable().WithCacheIF(useCache, cacheSecond).ToList(); } #endregion query #region add /// /// 插入实体 /// /// /// public int Add(T t, bool ignoreNull = true) { return Context.Insertable(t).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand(); } public int Insert(List t) { return Context.Insertable(t).ExecuteCommand(); } public int Insert(T parm, Expression> iClumns = null, bool ignoreNull = true) { return Context.Insertable(parm).InsertColumns(iClumns).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand(); } public IInsertable Insertable(T t) { return Context.Insertable(t); } #endregion add #region delete public IDeleteable Deleteable() { return Context.Deleteable(); } /// /// 批量删除 /// /// /// public int Delete(object[] obj) { return Context.Deleteable().In(obj).ExecuteCommand(); } public int Delete(object id) { return Context.Deleteable(id).ExecuteCommand(); } public int DeleteTable() { return Context.Deleteable().ExecuteCommand(); } public bool Truncate() { return Context.DbMaintenance.TruncateTable(); } #endregion delete public DbResult LoginUseTran(Action action) { try { var result = Context.Ado.UseTran(() => action(), error => { var err = error as BZSysExCore; Context.Ado.RollbackTran(); throw new BZSysExCore(err != null ? err.SysExType : 0, error.Message); }); return result; } catch (Exception ex) { Context.Ado.RollbackTran(); Console.WriteLine(ex.Message); throw; } } public DbResult UseTranAction(Action action) { var result = Context.Ado.UseTran(() => action(), error => { var err = error as BZSysExCore; Context.Ado.RollbackTran(); throw new BZSysExCore(err != null ? err.SysExType : 0, error.Message); }); return result; } public DbResult UseTran(Action action) { try { var result = Context.Ado.UseTran(() => action()); return result; } catch (Exception ex) { Context.Ado.RollbackTran(); Console.WriteLine(ex.Message); throw; } } public IStorageable Storageable(T t) { return Context.Storageable(t); } public IStorageable Storageable(List t) { return Context.Storageable(t); } /// /// /// /// /// 增删改查方法 /// public DbResult UseTran(SqlSugarClient client, Action action) { try { var result = client.AsTenant().UseTran(() => action()); return result; } catch (Exception ex) { client.AsTenant().RollbackTran(); Console.WriteLine(ex.Message); throw; } } /// /// 使用事务 /// /// /// public bool UseTran2(Action action) { var result = Context.Ado.UseTran(() => action()); return result.IsSuccess; } } }