BaseRepository.cs 14 KB

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