BaseRepository.cs 12 KB

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