BaseRepository.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. using Infrastructure.Extensions;
  2. using Mapster;
  3. using SqlSugar;
  4. using SqlSugar.IOC;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using ZR.Model;
  11. namespace ZR.Repository
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. /// <typeparam name="T"></typeparam>
  17. public class BaseRepository<T> : SimpleClient<T> where T : class, new()
  18. {
  19. public ITenant itenant = null;//多租户事务
  20. public BaseRepository(ISqlSugarClient context = null) : base(context)
  21. {
  22. //通过特性拿到ConfigId
  23. var configId = typeof(T).GetCustomAttribute<TenantAttribute>()?.configId;
  24. if (configId != null)
  25. {
  26. Context = DbScoped.SugarScope.GetConnectionScope(configId);//根据类传入的ConfigId自动选择
  27. }
  28. else
  29. {
  30. Context = context ?? DbScoped.SugarScope.GetConnectionScope(0);//没有默认db0
  31. }
  32. //Context = DbScoped.SugarScope.GetConnectionScopeWithAttr<T>();
  33. itenant = DbScoped.SugarScope;//设置租户接口
  34. }
  35. #region add
  36. /// <summary>
  37. /// 插入实体
  38. /// </summary>
  39. /// <param name="t"></param>
  40. /// <returns></returns>
  41. public int Add(T t, bool ignoreNull = true)
  42. {
  43. return Context.Insertable(t).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand();
  44. }
  45. public int Insert(List<T> t)
  46. {
  47. return Context.Insertable(t).ExecuteCommand();
  48. }
  49. public int Insert(T parm, Expression<Func<T, object>> iClumns = null, bool ignoreNull = true)
  50. {
  51. return Context.Insertable(parm).InsertColumns(iClumns).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand();
  52. }
  53. public IInsertable<T> Insertable(T t)
  54. {
  55. return Context.Insertable<T>(t);
  56. }
  57. #endregion add
  58. #region update
  59. public IUpdateable<T> Updateable(T entity)
  60. {
  61. return Context.Updateable(entity);
  62. }
  63. /// <summary>
  64. /// 实体根据主键更新
  65. /// </summary>
  66. /// <param name="entity"></param>
  67. /// <param name="ignoreNullColumns"></param>
  68. /// <returns></returns>
  69. public int Update(T entity, bool ignoreNullColumns = false)
  70. {
  71. return Context.Updateable(entity).IgnoreColumns(ignoreNullColumns).ExecuteCommand();
  72. }
  73. /// <summary>
  74. /// 实体根据主键更新指定字段
  75. /// return Update(user, t => new { t.NickName, }, true);
  76. /// </summary>
  77. /// <param name="entity"></param>
  78. /// <param name="expression"></param>
  79. /// <param name="ignoreAllNull"></param>
  80. /// <returns></returns>
  81. public int Update(T entity, Expression<Func<T, object>> expression, bool ignoreAllNull = false)
  82. {
  83. return Context.Updateable(entity).UpdateColumns(expression).IgnoreColumns(ignoreAllNull).ExecuteCommand();
  84. }
  85. /// <summary>
  86. /// 根据指定条件更新指定列 eg:Update(new SysUser(){ }, it => new { it.Status }, f => f.Userid == 1));
  87. /// 只更新Status列,条件是包含
  88. /// </summary>
  89. /// <param name="entity"></param>
  90. /// <param name="expression"></param>
  91. /// <param name="where"></param>
  92. /// <returns></returns>
  93. public int Update(T entity, Expression<Func<T, object>> expression, Expression<Func<T, bool>> where)
  94. {
  95. return Context.Updateable(entity).UpdateColumns(expression).Where(where).ExecuteCommand();
  96. }
  97. public int Update(SqlSugarClient client, T entity, Expression<Func<T, object>> expression, Expression<Func<T, bool>> where)
  98. {
  99. return client.Updateable(entity).UpdateColumns(expression).Where(where).ExecuteCommand();
  100. }
  101. /// <summary>
  102. ///
  103. /// </summary>
  104. /// <param name="entity"></param>
  105. /// <param name="list"></param>
  106. /// <param name="isNull">默认为true</param>
  107. /// <returns></returns>
  108. public int Update(T entity, List<string> list = null, bool isNull = true)
  109. {
  110. if (list == null)
  111. {
  112. list = new List<string>()
  113. {
  114. "Create_By",
  115. "Create_time"
  116. };
  117. }
  118. return Context.Updateable(entity).IgnoreColumns(isNull).IgnoreColumns(list.ToArray()).ExecuteCommand();
  119. }
  120. //public bool Update(List<T> entity)
  121. //{
  122. // var result = base.Context.Ado.UseTran(() =>
  123. // {
  124. // base.Context.Updateable(entity).ExecuteCommand();
  125. // });
  126. // return result.IsSuccess;
  127. //}
  128. /// <summary>
  129. /// 更新指定列 eg:Update(w => w.NoticeId == model.NoticeId, it => new SysNotice(){ Update_time = DateTime.Now, Title = "通知标题" });
  130. /// </summary>
  131. /// <param name="where"></param>
  132. /// <param name="columns"></param>
  133. /// <returns></returns>
  134. public int Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> columns)
  135. {
  136. return Context.Updateable<T>().SetColumns(columns).Where(where).RemoveDataCache().ExecuteCommand();
  137. }
  138. #endregion update
  139. public DbResult<bool> UseTran(Action action)
  140. {
  141. try
  142. {
  143. var result = Context.Ado.UseTran(() => action());
  144. return result;
  145. }
  146. catch (Exception ex)
  147. {
  148. Context.Ado.RollbackTran();
  149. Console.WriteLine(ex.Message);
  150. throw;
  151. }
  152. }
  153. public IStorageable<T> Storageable(T t)
  154. {
  155. return Context.Storageable<T>(t);
  156. }
  157. public IStorageable<T> Storageable(List<T> t)
  158. {
  159. return Context.Storageable(t);
  160. }
  161. /// <summary>
  162. ///
  163. /// </summary>
  164. /// <param name="client"></param>
  165. /// <param name="action">增删改查方法</param>
  166. /// <returns></returns>
  167. public DbResult<bool> UseTran(SqlSugarClient client, Action action)
  168. {
  169. try
  170. {
  171. var result = client.AsTenant().UseTran(() => action());
  172. return result;
  173. }
  174. catch (Exception ex)
  175. {
  176. client.AsTenant().RollbackTran();
  177. Console.WriteLine(ex.Message);
  178. throw;
  179. }
  180. }
  181. public bool UseTran2(Action action)
  182. {
  183. var result = Context.Ado.UseTran(() => action());
  184. return result.IsSuccess;
  185. }
  186. #region delete
  187. public IDeleteable<T> Deleteable()
  188. {
  189. return Context.Deleteable<T>();
  190. }
  191. /// <summary>
  192. /// 批量删除
  193. /// </summary>
  194. /// <param name="obj"></param>
  195. /// <returns></returns>
  196. public int Delete(object[] obj)
  197. {
  198. return Context.Deleteable<T>().In(obj).ExecuteCommand();
  199. }
  200. public int Delete(object id)
  201. {
  202. return Context.Deleteable<T>(id).ExecuteCommand();
  203. }
  204. public int DeleteTable()
  205. {
  206. return Context.Deleteable<T>().ExecuteCommand();
  207. }
  208. public bool Truncate()
  209. {
  210. return Context.DbMaintenance.TruncateTable<T>();
  211. }
  212. #endregion delete
  213. #region query
  214. public bool Any(Expression<Func<T, bool>> expression)
  215. {
  216. return Context.Queryable<T>().Where(expression).Any();
  217. }
  218. public ISugarQueryable<T> Queryable()
  219. {
  220. return Context.Queryable<T>();
  221. }
  222. public (List<T>, int) QueryableToPage(Expression<Func<T, bool>> expression, int pageIndex = 0, int pageSize = 10)
  223. {
  224. int totalNumber = 0;
  225. var list = Context.Queryable<T>().Where(expression).ToPageList(pageIndex, pageSize, ref totalNumber);
  226. return (list, totalNumber);
  227. }
  228. public (List<T>, int) QueryableToPage(Expression<Func<T, bool>> expression, string order, int pageIndex = 0, int pageSize = 10)
  229. {
  230. int totalNumber = 0;
  231. var list = Context.Queryable<T>().Where(expression).OrderBy(order).ToPageList(pageIndex, pageSize, ref totalNumber);
  232. return (list, totalNumber);
  233. }
  234. public (List<T>, int) QueryableToPage(Expression<Func<T, bool>> expression, Expression<Func<T, object>> orderFiled, string orderBy, int pageIndex = 0, int pageSize = 10)
  235. {
  236. int totalNumber = 0;
  237. if (orderBy.Equals("DESC", StringComparison.OrdinalIgnoreCase))
  238. {
  239. var list = Context.Queryable<T>().Where(expression).OrderBy(orderFiled, OrderByType.Desc).ToPageList(pageIndex, pageSize, ref totalNumber);
  240. return (list, totalNumber);
  241. }
  242. else
  243. {
  244. var list = Context.Queryable<T>().Where(expression).OrderBy(orderFiled, OrderByType.Asc).ToPageList(pageIndex, pageSize, ref totalNumber);
  245. return (list, totalNumber);
  246. }
  247. }
  248. public List<T> SqlQueryToList(string sql, object obj = null)
  249. {
  250. return Context.Ado.SqlQuery<T>(sql, obj);
  251. }
  252. /// <summary>
  253. /// 根据主值查询单条数据
  254. /// </summary>
  255. /// <param name="pkValue">主键值</param>
  256. /// <returns>泛型实体</returns>
  257. public T GetId(object pkValue)
  258. {
  259. return Context.Queryable<T>().InSingle(pkValue);
  260. }
  261. /// <summary>
  262. /// 根据条件查询分页数据
  263. /// </summary>
  264. /// <param name="where"></param>
  265. /// <param name="parm"></param>
  266. /// <returns></returns>
  267. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm)
  268. {
  269. var source = Context.Queryable<T>().Where(where);
  270. return source.ToPage(parm);
  271. }
  272. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm, Expression<Func<T, object>> order, OrderByType orderEnum = OrderByType.Asc)
  273. {
  274. var source = Context.Queryable<T>().Where(where).OrderByIF(orderEnum == OrderByType.Asc, order, OrderByType.Asc).OrderByIF(orderEnum == OrderByType.Desc, order, OrderByType.Desc);
  275. return source.ToPage(parm);
  276. }
  277. public PagedInfo<T> GetPages(Expression<Func<T, bool>> where, PagerInfo parm, Expression<Func<T, object>> order, string orderByType)
  278. {
  279. return GetPages(where, parm, order, orderByType == "desc" ? OrderByType.Desc : OrderByType.Asc);
  280. }
  281. /// <summary>
  282. /// 查询所有数据(无分页,请慎用)
  283. /// </summary>
  284. /// <returns></returns>
  285. public List<T> GetAll(bool useCache = false, int cacheSecond = 3600)
  286. {
  287. return Context.Queryable<T>().WithCacheIF(useCache, cacheSecond).ToList();
  288. }
  289. #endregion query
  290. /// <summary>
  291. /// 此方法不带output返回值
  292. /// var list = new List<SugarParameter>();
  293. /// list.Add(new SugarParameter(ParaName, ParaValue)); input
  294. /// </summary>
  295. /// <param name="procedureName"></param>
  296. /// <param name="parameters"></param>
  297. /// <returns></returns>
  298. public DataTable UseStoredProcedureToDataTable(string procedureName, List<SugarParameter> parameters)
  299. {
  300. return Context.Ado.UseStoredProcedure().GetDataTable(procedureName, parameters);
  301. }
  302. /// <summary>
  303. /// 带output返回值
  304. /// var list = new List<SugarParameter>();
  305. /// list.Add(new SugarParameter(ParaName, ParaValue, true)); output
  306. /// list.Add(new SugarParameter(ParaName, ParaValue)); input
  307. /// </summary>
  308. /// <param name="procedureName"></param>
  309. /// <param name="parameters"></param>
  310. /// <returns></returns>
  311. public (DataTable, List<SugarParameter>) UseStoredProcedureToTuple(string procedureName, List<SugarParameter> parameters)
  312. {
  313. var result = (Context.Ado.UseStoredProcedure().GetDataTable(procedureName, parameters), parameters);
  314. return result;
  315. }
  316. }
  317. /// <summary>
  318. /// 分页查询扩展
  319. /// </summary>
  320. public static class QueryableExtension
  321. {
  322. /// <summary>
  323. /// 读取列表
  324. /// </summary>
  325. /// <typeparam name="T"></typeparam>
  326. /// <param name="source">查询表单式</param>
  327. /// <param name="parm">分页参数</param>
  328. /// <returns></returns>
  329. public static PagedInfo<T> ToPage<T>(this ISugarQueryable<T> source, PagerInfo parm)
  330. {
  331. var page = new PagedInfo<T>();
  332. var total = 0;
  333. page.PageSize = parm.PageSize;
  334. page.PageIndex = parm.PageNum;
  335. page.Result = source.OrderByIF(parm.Sort.IsNotEmpty(), $"{parm.Sort.ToSqlFilter()} {(parm.SortType.Contains("desc") ? "desc" : "asc")}")
  336. .ToPageList(parm.PageNum, parm.PageSize, ref total);
  337. page.TotalNum = total;
  338. return page;
  339. }
  340. /// <summary>
  341. /// 转指定实体类Dto
  342. /// </summary>
  343. /// <typeparam name="T"></typeparam>
  344. /// <typeparam name="T2"></typeparam>
  345. /// <param name="source"></param>
  346. /// <param name="parm"></param>
  347. /// <returns></returns>
  348. public static PagedInfo<T2> ToPage<T, T2>(this ISugarQueryable<T> source, PagerInfo parm)
  349. {
  350. var page = new PagedInfo<T2>();
  351. var total = 0;
  352. page.PageSize = parm.PageSize;
  353. page.PageIndex = parm.PageNum;
  354. var result = source
  355. .OrderByIF(parm.Sort.IsNotEmpty(), $"{parm.Sort.ToSqlFilter()} {(parm.SortType.Contains("desc") ? "desc" : "asc")}")
  356. .ToPageList(parm.PageNum, parm.PageSize, ref total);
  357. page.TotalNum = total;
  358. page.Result = result.Adapt<List<T2>>();
  359. return page;
  360. }
  361. }
  362. }