当前位置:   article > 正文

八、Sqlsugar 通用方法整理

sqlsugar

一、新建泛型辅助类SqlSugarHelper.cs,用于创建数据库连接

  1. /// <summary>
  2. /// SqlSugar的辅助方法
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. public class SqlSugarHelper<T> where T : class, new()
  6. {
  7. //注意:不能写成静态的
  8. public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
  9. //public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }//用来操作当前表的数据
  10. public SqlSugarHelper()
  11. {
  12. Db = new SqlSugarClient(new ConnectionConfig()
  13. {
  14. ConnectionString = AppSettingFun.GetConnectionStr(),//数据库链接字符串
  15. DbType = DbType.SqlServer,//指定数据库类型
  16. IsAutoCloseConnection = true,//链接使用完后是否自动释放
  17. InitKeyType = InitKeyType.Attribute//从实体特性中读取主键自增列信息
  18. });
  19. //调式代码 用来打印SQL
  20. Db.Aop.OnLogExecuting = (sql, pars) =>
  21. {
  22. Console.WriteLine(sql + "\r\n" +
  23. Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  24. Console.WriteLine();
  25. };
  26. }
  27. }

二、整理数据库方法整理

  1. public class SqlSugarFun<T> : SqlSugarHelper<T> where T : class, new()
  2. {
  3. public SqlSugarClient db;
  4. public SqlSugarFun()
  5. {
  6. db = Db;
  7. }
  8. #region 保存(新增或更新)
  9. /// <summary>
  10. /// 保存(新增或更新)
  11. /// </summary>
  12. /// <param name="model">实体数据</param>
  13. /// <returns></returns>
  14. public async Task<bool> Save(T model)
  15. {
  16. return await Task.Run(() => db.Storageable(model).ExecuteCommandAsync()) > 0;
  17. }
  18. /// <summary>
  19. /// 保存数据集(新增或更新)
  20. /// </summary>
  21. /// <param name="model">实体数据集</param>
  22. /// <returns></returns>
  23. public async Task<int> Save(List<T> model)
  24. {
  25. return await Task.Run(() => db.Storageable(model).ExecuteCommandAsync());
  26. }
  27. #endregion
  28. #region 新增
  29. #region 新增
  30. /// <summary>
  31. /// 插入数据
  32. /// </summary>
  33. /// <param name="model">实体数据</param>
  34. /// <returns>是否成功</returns>
  35. public async Task<bool> AddModel(T model)
  36. {
  37. return await Task.Run(() => db.Insertable(model).ExecuteCommandAsync()) > 0;
  38. }
  39. /// <summary>
  40. ///多数据插入
  41. /// </summary>
  42. /// <param name="lst">实体集合数据</param>
  43. /// <returns>影响行数</returns>
  44. public async Task<int> AddModel(List<T> lst)
  45. {
  46. return await Task.Run(() => db.Insertable(lst).ExecuteCommandAsync());
  47. }
  48. /// <summary>
  49. /// 写入实体数据并返回最新实体
  50. /// </summary>
  51. /// <param name="model">实体数据</param>
  52. /// <returns>最新实体</returns>
  53. public async Task<T> AddbackEntity(T model)
  54. {
  55. return await Task.Run(() => db.Insertable(model).ExecuteReturnEntityAsync());
  56. }
  57. /// <summary>
  58. /// 写入实体数据并返回自增列
  59. /// </summary>
  60. /// <param name="model">实体数据</param>
  61. /// <returns>主键</returns>
  62. public async Task<int> AddbackIdentity(T model)
  63. {
  64. return await Task.Run(() => db.Insertable(model).ExecuteReturnIdentityAsync());
  65. }
  66. /// <summary>
  67. /// 单条插入返回雪花ID
  68. /// </summary>
  69. /// <param name="model">实体数据</param>
  70. /// <returns>雪花ID</returns>
  71. public async Task<long> AddbackSnowflakeid(T model)
  72. {
  73. return await Task.Run(() => db.Insertable(model).ExecuteReturnSnowflakeIdAsync());
  74. }
  75. /// <summary>
  76. /// 多条插入批量返回,比自增好用
  77. /// </summary>
  78. /// <param name="lst">实体集合数据</param>
  79. /// <returns>雪花ID集合</returns>
  80. public async Task<List<long>> AddbackSnowflakeid(List<T> lst)
  81. {
  82. return await Task.Run(() => db.Insertable(lst).ExecuteReturnSnowflakeIdListAsync());
  83. }
  84. #endregion
  85. #region 大数据新增
  86. /// <summary>
  87. /// 参数化内部分页插入(建议500行以下)
  88. /// </summary>
  89. /// <param name="model_lst">实体数据集合</param>
  90. /// <returns>影响行数</returns>
  91. public async Task<int> AddListParam(List<T> model_lst)
  92. {
  93. return await Task.Run(() => db.Insertable(model_lst).UseParameter().ExecuteCommandAsync());
  94. }
  95. /// <summary>
  96. /// 大数据写入(特色功能:大数据处理上比所有框架都要快30%)
  97. /// </summary>
  98. /// <param name="model_lst">实体数据集合</param>
  99. /// <returns>影响行数</returns>
  100. public async Task<int> AddListMax(List<T> model_lst)
  101. {
  102. return await Task.Run(() => db.Fastest<T>().BulkCopyAsync(model_lst));
  103. }
  104. #endregion
  105. #endregion
  106. #region 删除
  107. #region 删除
  108. /// <summary>
  109. /// 根据主键删除
  110. /// </summary>
  111. /// <param name="id">主键</param>
  112. /// <returns>是否成功</returns>
  113. public async Task<bool> Delete(object id)
  114. {
  115. return await Task.Run(() => db.Deleteable<T>().In(id).ExecuteCommandHasChangeAsync());
  116. }
  117. /// <summary>
  118. /// 根据主键数组批量删除
  119. /// </summary>
  120. /// <param name="ids">主键数组</param>
  121. /// <returns>影响行数</returns>
  122. public async Task<int> Delete(object[] ids)
  123. {
  124. return await Task.Run(() => db.Deleteable<T>().In(ids).ExecuteCommandAsync());
  125. }
  126. /// <summary>
  127. /// 根据实体删除
  128. /// </summary>
  129. /// <param name="model">实体数据,有主键就行</param>
  130. /// <returns>是否成功</returns>
  131. public async Task<bool> Delete(T model)
  132. {
  133. return await Task.Run(() => db.Deleteable<T>().Where(model).ExecuteCommandHasChangeAsync());
  134. }
  135. /// <summary>
  136. /// 批量删除实体
  137. /// </summary>
  138. /// <param name="lst">实体集合数据,有主键就行</param>
  139. /// <returns>影响行数</returns>
  140. public async Task<int> Delete(List<T> lst)
  141. {
  142. return await Task.Run(() => db.Deleteable<T>(lst).ExecuteCommandAsync());
  143. }
  144. /// <summary>
  145. /// 根据条件删除
  146. /// </summary>
  147. /// <param name="where"></param>
  148. /// <returns>是否成功</returns>
  149. public async Task<bool> Delete(Expression<Func<T, bool>> where)
  150. {
  151. return await Task.Run(() => db.Deleteable<T>().Where(where).ExecuteCommandHasChangeAsync());
  152. }
  153. #endregion
  154. #region 假删除
  155. /// <summary>
  156. /// 根据主键假删除, 要求实体属性中必须有isdelete或者isdeleted
  157. /// </summary>
  158. /// <param name="id">主键</param>
  159. /// <returns>是否成功</returns>
  160. public async Task<bool> DeleteLogic(object id)
  161. {
  162. return await Task.Run(() => db.Deleteable<T>().In(id).IsLogic().ExecuteCommandAsync()) > 0;
  163. }
  164. /// <summary>
  165. /// 根据主键指定属性假删除
  166. /// </summary>
  167. /// <param name="id">主键</param>
  168. /// <param name="name">属性名称</param>
  169. /// <returns>是否成功</returns>
  170. public async Task<bool> DeleteLogic(object id, string name)
  171. {
  172. return await Task.Run(() => db.Deleteable<T>().In(id).IsLogic().ExecuteCommandAsync(name)) > 0;
  173. }
  174. /// <summary>
  175. /// 根据主键数组批量假删除
  176. /// </summary>
  177. /// <param name="ids">主键数组</param>
  178. /// <returns>影响行数</returns>
  179. public async Task<int> DeleteLogic(object[] ids)
  180. {
  181. return await Task.Run(() => db.Deleteable<T>().In(ids).IsLogic().ExecuteCommandAsync());
  182. }
  183. /// <summary>
  184. /// 根据主键数组指定属性批量假删除
  185. /// </summary>
  186. /// <param name="ids">主键数组</param>
  187. /// <returns>影响行数</returns>
  188. public async Task<int> DeleteLogic(object[] ids, string name)
  189. {
  190. return await Task.Run(() => db.Deleteable<T>().In(ids).IsLogic().ExecuteCommandAsync(name));
  191. }
  192. /// <summary>
  193. /// 根据条件指定属性假删除
  194. /// </summary>
  195. /// <param name="where">条件表达式</param>
  196. /// <param name="name">删除字段名称</param>
  197. /// <returns>影响行数</returns>
  198. public async Task<int> DeleteLogic(Expression<Func<T, bool>> where, string delcol)
  199. {
  200. return await Task.Run(() => db.Deleteable<T>().Where(where).IsLogic().ExecuteCommandAsync(delcol));
  201. }
  202. /// <summary>
  203. /// 根据主键删除并更新操作时间
  204. /// </summary>
  205. /// <param name="id">主键</param>
  206. /// <param name="delcol">删除标记字段</param>
  207. /// <param name="datecol">时间标记字段</param>
  208. /// <returns>是否成功</returns>
  209. public async Task<bool> DeleteLogic(object id, string delcol, string datecol)
  210. {
  211. return await Task.Run(() => db.Deleteable<T>().In(id).IsLogic().ExecuteCommand(delcol, DateTime.Now, datecol)) > 0;
  212. }
  213. /// <summary>
  214. /// 根据主键批量删除并更新操作时间
  215. /// </summary>
  216. /// <param name="id">主键</param>
  217. /// <param name="delcol">删除标记字段</param>
  218. /// <param name="datecol">时间标记字段</param>
  219. /// <returns>影响行数</returns>
  220. public async Task<int> DeleteLogic(object[] ids, string delcol, string datecol)
  221. {
  222. return await Task.Run(() => db.Deleteable<T>().In(ids).IsLogic().ExecuteCommand(delcol, DateTime.Now, datecol));
  223. }
  224. #endregion
  225. #endregion
  226. #region 更新
  227. /// <summary>
  228. /// 更新实体数据
  229. /// </summary>
  230. /// <param name="model">实体数据</param>
  231. /// <returns>是否成功</returns>
  232. public async Task<bool> Update(T model)
  233. {
  234. //这种方式会以主键为条件
  235. return await Task.Run(() => db.Updateable(model).ExecuteCommandHasChange());
  236. }
  237. /// <summary>
  238. /// 批量更新实体数据
  239. /// 数据超过50条时启用大数据更新
  240. /// </summary>
  241. /// <param name="lst">实体集合</param>
  242. /// <returns>影响行数</returns>
  243. public async Task<int> Update(List<T> lst)
  244. {
  245. if (lst.Count > 50)
  246. {
  247. return await Task.Run(() => db.Fastest<T>().BulkUpdateAsync(lst));
  248. }
  249. //这种方式会以主键为条件
  250. return await Task.Run(() => db.Updateable(lst).ExecuteCommandAsync());
  251. }
  252. /// <summary>
  253. /// 按条件指定更新列
  254. /// </summary>
  255. /// <param name="newObject">t=>t.更新列==值 表达式</param>
  256. /// <param name="where">条件表达式</param>
  257. /// <returns>影响行数</returns>
  258. public async Task<int> Update(Expression<Func<T, bool>> newObject, Expression<Func<T, bool>> where)
  259. {
  260. return await Task.Run(() => db.Updateable<T>().SetColumns(newObject).Where(where).ExecuteCommandAsync());
  261. }
  262. /// <summary>
  263. /// 按条件指定更新列
  264. /// </summary>
  265. /// <param name="newObject">t=> new T(){更新列=值} 表达式</param>
  266. /// <param name="where">条件表达式</param>
  267. /// <returns>影响行数</returns>
  268. public async Task<int> Update(Expression<Func<T, T>> newObject, Expression<Func<T, bool>> where)
  269. {
  270. return await Task.Run(() => db.Updateable<T>().SetColumns(newObject).Where(where).ExecuteCommandAsync());
  271. }
  272. /// <summary>
  273. /// 更新并启用启用验证
  274. /// 需要有Timestamp字段呼应
  275. /// </summary>
  276. /// <param name="model"></param>
  277. /// <returns></returns>
  278. public async Task<bool> UpdateVer(T model)
  279. {
  280. return await Task.Run(() => db.Updateable(model).IsEnableUpdateVersionValidation().ExecuteCommandHasChange());
  281. }
  282. #endregion
  283. #region 查询
  284. #region 基础查询
  285. /// <summary>
  286. /// 获取所有数据
  287. /// </summary>
  288. /// <returns></returns>
  289. public async Task<List<T>> GetAll()
  290. {
  291. return await Task.Run(() => db.Queryable<T>().ToList());
  292. }
  293. /// <summary>
  294. /// 根据主键获取数据
  295. /// </summary>
  296. /// <param name="objId"></param>
  297. /// <returns></returns>
  298. public async Task<T> QueryByID(object objId)
  299. {
  300. return await Task.Run(() => db.Queryable<T>().InSingleAsync(objId));
  301. }
  302. /// <summary>
  303. /// 根据条件查询数据
  304. /// var exp= Expressionable.Create<Student>();
  305. /// exp.OrIF(条件,it=>it.Id==1);//.OrIf 是条件成立才会拼接OR
  306. /// exp.Or(it =>it.Name.Contains("jack"));//拼接OR
  307. /// var list =db.Queryable<Student>().Where(exp.ToExpression()).ToList();
  308. /// </summary>
  309. /// <param name="expression"></param>
  310. /// <returns></returns>
  311. public async Task<T> QueryByWhere(Expression<Func<T, bool>> where)
  312. {
  313. return await Task.Run(() => db.Queryable<T>().Where(where).First());
  314. }
  315. /// <summary>
  316. /// 查询是否存在
  317. /// </summary>
  318. /// <param name="where"></param>
  319. /// <returns></returns>
  320. public async Task<bool> Any(Expression<Func<T, bool>> where)
  321. {
  322. return await Task.Run(() => db.Queryable<T>().AnyAsync(where));
  323. }
  324. /// <summary>
  325. /// 获取正序数据集合
  326. /// </summary>
  327. /// <param name="where"></param>
  328. /// <returns></returns>
  329. public async Task<List<T>> GetListByAsc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order)
  330. {
  331. return await Task.Run(() => db.Queryable<T>().Where(where).OrderBy(order).ToList());
  332. }
  333. /// <summary>
  334. /// 获取反序数据集合
  335. /// </summary>
  336. /// <param name="where"></param>
  337. /// <returns></returns>
  338. public async Task<List<T>> GetListByDesc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order)
  339. {
  340. return await Task.Run(() => db.Queryable<T>().Where(where).OrderBy(order, OrderByType.Desc).ToList());
  341. }
  342. #endregion
  343. #region 分页查询
  344. /// <summary>
  345. /// 分页正序查询
  346. /// SqlSever2012分页 把 ToPageList 换成 ToOffsetPage //offest分页
  347. /// </summary>
  348. /// <param name="where"></param>
  349. /// <param name="order"></param>
  350. /// <param name="pageindex"></param>
  351. /// <param name="pagerow"></param>
  352. /// <param name="count"></param>
  353. /// <returns></returns>
  354. public List<T> GetPageListByAsc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, int pageindex, int pagerow, ref int count)
  355. {
  356. return db.Queryable<T>().Where(where).OrderBy(order).ToPageList(pageindex, pagerow, ref count);
  357. }
  358. /// <summary>
  359. /// 分页反序查询
  360. /// </summary>
  361. /// <param name="where"></param>
  362. /// <param name="order"></param>
  363. /// <param name="pageindex"></param>
  364. /// <param name="pagerow"></param>
  365. /// <param name="count"></param>
  366. /// <returns></returns>
  367. public List<T> GetPageListByDesc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, int pageindex, int pagerow, ref int count)
  368. {
  369. return db.Queryable<T>().Where(where).OrderBy(order, OrderByType.Desc).ToPageList(pageindex, pagerow, ref count);
  370. }
  371. /// <summary>
  372. /// 分页正序查询
  373. /// SqlSever2012分页 把 ToPageList 换成 ToOffsetPage //offest分页
  374. /// </summary>
  375. /// <param name="where"></param>
  376. /// <param name="order"></param>
  377. /// <param name="select"></param>
  378. /// <param name="pageindex"></param>
  379. /// <param name="pagerow"></param>
  380. /// <param name="count"></param>
  381. /// <returns></returns>
  382. public List<object> GetPageListByAsc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, Expression<Func<T, object>> select, int pageindex, int pagerow, ref int count)
  383. {
  384. return db.Queryable<T>().Where(where).OrderBy(order).Select(select).ToPageList(pageindex, pagerow, ref count);
  385. }
  386. /// <summary>
  387. /// 分页反序查询
  388. /// </summary>
  389. /// <param name="where"></param>
  390. /// <param name="order"></param>
  391. /// <param name="select"></param>
  392. /// <param name="pageindex"></param>
  393. /// <param name="pagerow"></param>
  394. /// <param name="count"></param>
  395. /// <returns></returns>
  396. public List<object> GetPageListByDesc(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, Expression<Func<T, object>> select, int pageindex, int pagerow, ref int count)
  397. {
  398. return db.Queryable<T>().Where(where).OrderBy(order, OrderByType.Desc).Select(select).ToPageList(pageindex, pagerow, ref count);
  399. }
  400. /// <summary>
  401. /// 获取数据总页数
  402. /// </summary>
  403. /// <param name="where"></param>
  404. /// <param name="pageIndex"></param>
  405. /// <param name="pageSize"></param>
  406. /// <returns></returns>
  407. public int GetPageTotle(int count, int pagerow)
  408. {
  409. int total = count;
  410. if (total % pagerow > 0)
  411. total = total / pagerow + 1;
  412. else
  413. total /= pagerow;
  414. return total;
  415. }
  416. #endregion
  417. #endregion
  418. #region 其它方法
  419. /// <summary>
  420. /// 获取数据库时间
  421. /// </summary>
  422. /// <returns></returns>
  423. public async Task<DateTime> GetdbDate()
  424. {
  425. return await Task.Run(() => db.GetDate());
  426. }
  427. /// <summary>
  428. /// 执行SQL查询
  429. /// </summary>
  430. /// <param name="sql"></param>
  431. /// <returns></returns>
  432. public async Task<dynamic> SqlQuery(string sql)
  433. {
  434. return await Task.Run(() => db.Ado.SqlQuery<dynamic>(sql));
  435. }
  436. /// <summary>
  437. /// 执行sql语句(查询除外)
  438. /// </summary>
  439. /// <param name="sql"></param>
  440. /// <returns></returns>
  441. public async Task<bool> SqlExec(string sql)
  442. {
  443. return await Task.Run(() => db.Ado.ExecuteCommand(sql)) > 0;
  444. }
  445. /// <summary>
  446. /// 获取新的雪花ID
  447. /// </summary>
  448. /// <returns></returns>
  449. public async Task<long> GetSnowFlakeID()
  450. {
  451. return await Task.Run(() => SnowFlakeSingle.Instance.NextId());
  452. }
  453. /// <summary>
  454. /// 初始化表
  455. /// 表中数据全部清空,清除,自增初始化
  456. /// </summary>
  457. /// <returns>是否成功</returns>
  458. public async Task<bool> Truncate()
  459. {
  460. return await Task.Run(() => db.DbMaintenance.TruncateTable<T>());
  461. }
  462. #endregion
  463. }

三、调用实例

  1. //数据库实体 Entity
  2. public class OrderService : SqlSugarFun<Entity>
  3. {
  4. /// <summary>
  5. /// 多删
  6. /// </summary>
  7. /// <param name="id"></param>
  8. /// <param name="accountID"></param>
  9. /// <param name="businessUserID"></param>
  10. /// <returns></returns>
  11. public async Task<string> DelOrder(object[] id)
  12. {
  13. var od = await Task.Run(() => GetListByAsc(t => id.Contains(t.FID), t => t.FID));
  14. if (od == null)
  15. {
  16. return "找不到";
  17. }
  18. var b = await Task.Run(() => Delete(od)) > 0;
  19. if (b)
  20. return result.Success("操作成功");
  21. return result.Error("操作失败");
  22. }
  23. /// <summary>
  24. /// 数据库联查
  25. /// </summary>
  26. /// <param name="year"></param>
  27. /// <param name="month"></param>
  28. /// <param name="accountID"></param>
  29. /// <param name="private_key"></param>
  30. /// <returns></returns>
  31. public async Task<Object> GroupPerformanceRanking(int year, int month, long accountID)
  32. {
  33. DateTime start = Convert.ToDateTime($@"{year}-{month}-01 00:00:00");
  34. DateTime end = start.AddMonths(1);
  35. var lst = await Task.Run(() => db.Queryable<tOrder, tGroup>((o, g) => new JoinQueryInfos(
  36. JoinType.Left, o.FGroupID.Equals(g.FID)
  37. ))
  38. .Where((o, g) => o.FAccounID.Equals(accountID) && o.FOrderDate > start && o.FOrderDate < end)
  39. .Select((o, g) => new
  40. {
  41. g.FGroupName,
  42. g.FGroupLogo,
  43. o.FDollar,
  44. o.FRMB,
  45. }).MergeTable().GroupBy(g => new
  46. {
  47. g.FGroupName,
  48. g.FGroupLogo
  49. }).Select(t => new
  50. {
  51. t.FGroupName,
  52. FDollar = SqlFunc.AggregateSum(t.FDollar),
  53. FRMB = SqlFunc.AggregateSum(t.FRMB)
  54. }).OrderBy(t => t.FRMB, OrderByType.Desc).ToList());
  55. return result.Success(lst);
  56. }
  57. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/134822
推荐阅读
相关标签
  

闽ICP备14008679号