BaseRepository.cs 14 KB

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