PTRepository.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. using SqlSugar;
  2. using System.Linq.Expressions;
  3. using WMS.BZModels;
  4. using WMS.BZServices;
  5. using WMS.BZSqlSugar;
  6. namespace WMS.BZSqlSugar
  7. {
  8. public class PTRepository<T> : SimpleClient<T> where T : BaseEntityModel, new()
  9. {
  10. public PTRepository()
  11. {
  12. var lists = Util.ConfigHelper.GetConnectionConfigs().Connections;
  13. var connection = lists.FirstOrDefault(o => o.ConfigId == "pt");
  14. if (connection == null) { throw new Exception("DB 初始化错误。"); }
  15. Context = new SqlSugarScope(new ConnectionConfig()
  16. {
  17. DbType = (DbType)connection.DataBaseType,
  18. ConnectionString = connection.ConnectionString,
  19. IsAutoCloseConnection = connection.IsAutoCloseConn,
  20. },
  21. db =>
  22. {
  23. //单例参数配置,所有上下文生效
  24. db.Aop.OnLogExecuting = (sql, pars) =>
  25. {
  26. string log = $"【PT SQL语句】{UtilMethods.GetSqlString((DbType)connection.DataBaseType, sql, pars)}\n";
  27. if (sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  28. {
  29. Console.WriteLine(log);
  30. }
  31. else if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  32. {
  33. Console.WriteLine(log);
  34. }
  35. else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase))
  36. {
  37. Console.WriteLine(log);
  38. }
  39. else
  40. {
  41. log = $"【PT SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n";
  42. Console.WriteLine(log);
  43. }
  44. };
  45. });
  46. }
  47. private object GetParsValue(SugarParameter x)
  48. {
  49. if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String)
  50. {
  51. return "'" + x.Value + "'";
  52. }
  53. return x.Value;
  54. }
  55. /// <summary>
  56. ///
  57. /// </summary>
  58. /// <param name="t"></param>
  59. /// <returns></returns>
  60. public override T InsertReturnEntity(T t)
  61. {
  62. //t = CheckId.InitId<T>(t);
  63. return Context.Insertable(t).ExecuteReturnEntity();
  64. }
  65. /// <summary>
  66. /// 该方法默认不更新AddWho,AddTime
  67. /// </summary>
  68. /// <param name="entity"></param>
  69. /// <returns></returns>
  70. public bool UpdateEntity(T entity)
  71. {
  72. return Context.Updateable(entity).IgnoreColumns(new string[] { "AddWho", "AddTime" }).ExecuteCommand() > 0;
  73. }
  74. public bool UpdateModelColumns(Expression<Func<T, T>> Columns, Expression<Func<T, bool>> WhereExpression)
  75. {
  76. return Update(Columns, WhereExpression);
  77. }
  78. public T GetModelByExpression(Expression<Func<T, bool>> WhereExpression)
  79. {
  80. return GetSingle(WhereExpression);
  81. }
  82. //public ISugarQueryable<T> Queryable()
  83. //{
  84. // return Context.Queryable<T>();
  85. //}
  86. #region query
  87. public bool Any(Expression<Func<T, bool>> expression)
  88. {
  89. return Context.Queryable<T>().Where(expression).Any();
  90. }
  91. public ISugarQueryable<T> Queryable()
  92. {
  93. return Context.Queryable<T>();
  94. }
  95. public List<T> SqlQueryToList(string sql, object obj = null)
  96. {
  97. return Context.Ado.SqlQuery<T>(sql, obj);
  98. }
  99. /// <summary>
  100. /// 根据主值查询单条数据
  101. /// </summary>
  102. /// <param name="pkValue">主键值</param>
  103. /// <returns>泛型实体</returns>
  104. public T GetId(object pkValue)
  105. {
  106. return Context.Queryable<T>().InSingle(pkValue);
  107. }
  108. /// <summary>
  109. /// 根据条件查询分页数据
  110. /// </summary>
  111. /// <param name="where"></param>
  112. /// <param name="parm"></param>
  113. /// <returns></returns>
  114. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm)
  115. {
  116. var source = Context.Queryable<T>().Where(where);
  117. return source.ToPage(parm);
  118. }
  119. /// <summary>
  120. /// 分页获取数据
  121. /// </summary>
  122. /// <param name="where">条件表达式</param>
  123. /// <param name="parm"></param>
  124. /// <param name="order"></param>
  125. /// <param name="orderEnum"></param>
  126. /// <returns></returns>
  127. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm, Expression<Func<T, object>> order, OrderByType orderEnum = OrderByType.Asc)
  128. {
  129. var source = Context
  130. .Queryable<T>()
  131. .Where(where)
  132. .OrderByIF(orderEnum == OrderByType.Asc, order, OrderByType.Asc)
  133. .OrderByIF(orderEnum == OrderByType.Desc, order, OrderByType.Desc);
  134. return source.ToPage(parm);
  135. }
  136. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm, Expression<Func<T, object>> order, string orderByType)
  137. {
  138. return GetPages(where, parm, order, orderByType == "desc" ? OrderByType.Desc : OrderByType.Asc);
  139. }
  140. /// <summary>
  141. /// 查询所有数据(无分页,请慎用)
  142. /// </summary>
  143. /// <returns></returns>
  144. public List<T> GetAll(bool useCache = false, int cacheSecond = 3600)
  145. {
  146. return Context.Queryable<T>().WithCacheIF(useCache, cacheSecond).ToList();
  147. }
  148. #endregion query
  149. #region add
  150. /// <summary>
  151. /// 插入实体
  152. /// </summary>
  153. /// <param name="t"></param>
  154. /// <returns></returns>
  155. public int Add(T t, bool ignoreNull = true)
  156. {
  157. return Context.Insertable(t).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand();
  158. }
  159. public int Insert(List<T> t)
  160. {
  161. return Context.Insertable(t).ExecuteCommand();
  162. }
  163. public int Insert(T parm, Expression<Func<T, object>> iClumns = null, bool ignoreNull = true)
  164. {
  165. return Context.Insertable(parm).InsertColumns(iClumns).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand();
  166. }
  167. public IInsertable<T> Insertable(T t)
  168. {
  169. return Context.Insertable(t);
  170. }
  171. #endregion add
  172. #region delete
  173. public IDeleteable<T> Deleteable()
  174. {
  175. return Context.Deleteable<T>();
  176. }
  177. /// <summary>
  178. /// 批量删除
  179. /// </summary>
  180. /// <param name="obj"></param>
  181. /// <returns></returns>
  182. public int Delete(object[] obj)
  183. {
  184. return Context.Deleteable<T>().In(obj).ExecuteCommand();
  185. }
  186. public int Delete(object id)
  187. {
  188. return Context.Deleteable<T>(id).ExecuteCommand();
  189. }
  190. public int DeleteTable()
  191. {
  192. return Context.Deleteable<T>().ExecuteCommand();
  193. }
  194. public bool Truncate()
  195. {
  196. return Context.DbMaintenance.TruncateTable<T>();
  197. }
  198. #endregion delete
  199. public DbResult<bool> LoginUseTran(Action action)
  200. {
  201. try
  202. {
  203. var result = Context.Ado.UseTran(() => action(), error =>
  204. {
  205. var err = error as BZSysExCore;
  206. Context.Ado.RollbackTran();
  207. throw new BZSysExCore(err != null ? err.SysExType : 0, error.Message);
  208. });
  209. return result;
  210. }
  211. catch (Exception ex)
  212. {
  213. Context.Ado.RollbackTran();
  214. Console.WriteLine(ex.Message);
  215. throw;
  216. }
  217. }
  218. public DbResult<bool> UseTranAction(Action action)
  219. {
  220. var result = Context.Ado.UseTran(() => action(), error =>
  221. {
  222. var err = error as BZSysExCore;
  223. Context.Ado.RollbackTran();
  224. throw new BZSysExCore(err != null ? err.SysExType : 0, error.Message);
  225. });
  226. return result;
  227. }
  228. public DbResult<bool> UseTran(Action action)
  229. {
  230. try
  231. {
  232. var result = Context.Ado.UseTran(() => action());
  233. return result;
  234. }
  235. catch (Exception ex)
  236. {
  237. Context.Ado.RollbackTran();
  238. Console.WriteLine(ex.Message);
  239. throw;
  240. }
  241. }
  242. public IStorageable<T> Storageable(T t)
  243. {
  244. return Context.Storageable(t);
  245. }
  246. public IStorageable<T> Storageable(List<T> t)
  247. {
  248. return Context.Storageable(t);
  249. }
  250. /// <summary>
  251. ///
  252. /// </summary>
  253. /// <param name="client"></param>
  254. /// <param name="action">增删改查方法</param>
  255. /// <returns></returns>
  256. public DbResult<bool> UseTran(SqlSugarClient client, Action action)
  257. {
  258. try
  259. {
  260. var result = client.AsTenant().UseTran(() => action());
  261. return result;
  262. }
  263. catch (Exception ex)
  264. {
  265. client.AsTenant().RollbackTran();
  266. Console.WriteLine(ex.Message);
  267. throw;
  268. }
  269. }
  270. /// <summary>
  271. /// 使用事务
  272. /// </summary>
  273. /// <param name="action"></param>
  274. /// <returns></returns>
  275. public bool UseTran2(Action action)
  276. {
  277. var result = Context.Ado.UseTran(() => action());
  278. return result.IsSuccess;
  279. }
  280. }
  281. }