当前位置:   article > 正文

C# ORM模式之 SqlSugar使用_c# sqlsugar

c# sqlsugar

一、SqlSugar介绍及分析

SqlSugar是一款 老牌 .NET 开源ORM框架,连接DB特别方便

支持数据库:MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、人大金仓

官方文档:http://www.donet5.com/Home/Doc

SqlSugar的优点:

1、高性能:不夸张的说,去掉Sql在数据库执行的时间,SqlSugar是EF数倍性能,另外在批量操作和一对多查询上也有不错的SQL优化;

2、高扩展性 :支持自定义拉姆达函数解析、扩展数据类型、支持自定义实体特性,外部缓存等;

3、稳定性和技术支持:  虽然不是官方ORM, 但在稳定性上也是有着数年用户积累,如果遇到问题可以在GITHUB提出来,会根据紧急度定期解决;

4、功能全面:虽然SqlSugar小巧可功能并不逊色于EF框架

5、创新、持续更新 ,向下兼容

二、SqlSugar项目中的使用

1、包的引用:

 2、全局引用:

3、接口中常用方法封装

1)、ISqlSugarRepository接口封装

  1. public interface ISqlSugarRepository<TEntity> : IBaseRepository where TEntity : class
  2. {
  3. /// <summary>
  4. ///
  5. /// </summary>
  6. ISqlSugarClient Db { get; }
  7. /// <summary>
  8. /// 执行查询SQL语句
  9. /// 只支持查询操作,并且支持拉姆达分页
  10. /// </summary>
  11. /// <param name="sql"></param>
  12. /// <returns></returns>
  13. Task<List<TEntity>> ExecuteSql(string sql);
  14. /// <summary>
  15. /// 通过Ado方法执行SQL语句
  16. /// 支持任何SQL语句
  17. /// </summary>
  18. /// <param name="sql"></param>
  19. /// <param name="whereObj"></param>
  20. /// <returns></returns>
  21. Task<List<TEntity>> ExecuteAllSql(string sql, object whereObj = null);
  22. /// <summary>
  23. /// 插入实体
  24. /// </summary>
  25. /// <param name="model"></param>
  26. /// <returns></returns>
  27. Task<int> Add(TEntity model);
  28. /// <summary>
  29. /// 批量插入实体
  30. /// </summary>
  31. /// <param name="listEntity"></param>
  32. /// <returns></returns>
  33. Task<int> Add(List<TEntity> listEntity);
  34. /// <summary>
  35. /// 根据实体删除数据
  36. /// </summary>
  37. /// <param name="model"></param>
  38. /// <returns></returns>
  39. Task<bool> Delete(TEntity model);
  40. /// <summary>
  41. /// 根据实体集合批量删除数据
  42. /// </summary>
  43. /// <param name="models"></param>
  44. /// <returns></returns>
  45. Task<bool> Delete(List<TEntity> models);
  46. /// <summary>
  47. /// 根据ID删除数据
  48. /// </summary>
  49. /// <param name="id"></param>
  50. /// <returns></returns>
  51. Task<bool> DeleteById(object id);
  52. /// <summary>
  53. /// 根据IDs批量删除数据
  54. /// </summary>
  55. /// <param name="ids"></param>
  56. /// <returns></returns>
  57. Task<bool> DeleteByIds(List<object> ids);
  58. /// <summary>
  59. /// 更新实体
  60. /// </summary>
  61. /// <param name="model"></param>
  62. /// <returns></returns>
  63. Task<bool> Update(TEntity model);
  64. /// <summary>
  65. /// 批量更新实体
  66. /// </summary>
  67. /// <param name="listEntity"></param>
  68. /// <returns></returns>
  69. Task<int> Update(List<TEntity> listEntity);
  70. /// <summary>
  71. /// 根据ID查询一条数据
  72. /// </summary>
  73. /// <param name="objId"></param>
  74. /// <returns></returns>
  75. Task<TEntity> GetById(object objId);
  76. /// <summary>
  77. /// 根据条件查询数据是否存在
  78. /// </summary>
  79. /// <param name="whereExpression"></param>
  80. /// <returns></returns>
  81. Task<bool> GetAnyByFilter(Expression<Func<TEntity, bool>> whereExpression);
  82. /// <summary>
  83. /// 根据IDs查询数据
  84. /// </summary>
  85. /// <param name="lstIds"></param>
  86. /// <returns></returns>
  87. Task<List<TEntity>> GetByIds(List<object> lstIds);
  88. /// <summary>
  89. /// 根据条件查询一条数据
  90. /// </summary>
  91. /// <param name="whereExpression"></param>
  92. /// <returns></returns>
  93. Task<TEntity> GetSingleByFilter(Expression<Func<TEntity, bool>> whereExpression);
  94. /// <summary>
  95. /// 查询所有数据
  96. /// </summary>
  97. /// <returns></returns>
  98. Task<List<TEntity>> Get();
  99. /// <summary>
  100. /// 查询数据列表
  101. /// </summary>
  102. /// <param name="whereExpression">条件表达式</param>
  103. /// <returns>数据列表</returns>
  104. Task<List<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression);
  105. /// <summary>
  106. /// 查询数据列表
  107. /// </summary>
  108. /// <param name="whereExpression">条件表达式</param>
  109. /// <param name="orderByExpression">排序表达式</param>
  110. /// <param name="isAsc">是否升序排序</param>
  111. /// <returns></returns>
  112. Task<List<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, bool isAsc = true);
  113. /// <summary>
  114. /// 分页查询
  115. /// </summary>
  116. /// <param name="selector"></param>
  117. /// <param name="whereExpression"></param>
  118. /// <param name="intPageIndex"></param>
  119. /// <param name="intPageSize"></param>
  120. /// <param name="orderDescSelector"></param>
  121. /// <returns></returns>
  122. Task<PaginatedViewModel<TResult>> Get<TResult>(Expression<Func<TEntity, TResult>> selector, Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, Expression<Func<TEntity, object>> orderDescSelector = null);
  123. /// <summary>
  124. /// 分页查询
  125. /// </summary>
  126. /// <param name="selector"></param>
  127. /// <param name="whereExpression"></param>
  128. /// <param name="intPageIndex"></param>
  129. /// <param name="intPageSize"></param>
  130. /// <param name="orderDescSelector"></param>
  131. /// <returns></returns>
  132. Task<PaginatedViewModel<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, Expression<Func<TEntity, object>> orderDescSelector = null);
  133. }
public interface IBaseRepository { }

 事务接口:

  1. public interface IUnitOfWork
  2. {
  3. /// <summary>
  4. ///
  5. /// </summary>
  6. /// <returns></returns>
  7. SqlSugarClient GetDbClient();
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. void BeginTran();
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. void CommitTran();
  16. /// <summary>
  17. ///
  18. /// </summary>
  19. void RollbackTran();
  20. }

2)、SqlSugarRepository接口实现

  1. /// <summary>
  2. ///
  3. /// </summary>
  4. /// <typeparam name="TEntity"></typeparam>
  5. public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity> where TEntity : class, new()
  6. {
  7. private readonly SqlSugarClient _dbBase;
  8. public ISqlSugarClient Db
  9. {
  10. get { return _dbBase; }
  11. }
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. /// <param name="unitOfWork"></param>
  16. public SqlSugarRepository(IUnitOfWork unitOfWork)
  17. {
  18. _dbBase = unitOfWork.GetDbClient();
  19. }
  20. /// <summary>
  21. /// 执行查询SQL语句
  22. /// 只支持查询操作,并且支持拉姆达分页
  23. /// </summary>
  24. /// <param name="sql"></param>
  25. /// <returns></returns>
  26. public async Task<List<TEntity>> ExecuteSql(string sql)
  27. {
  28. return await Db.SqlQueryable<TEntity>(sql).ToListAsync();
  29. }
  30. /// <summary>
  31. /// 通过Ado方法执行SQL语句
  32. /// 支持任何SQL语句
  33. /// </summary>
  34. /// <param name="sql"></param>
  35. /// <param name="whereObj">参数</param>
  36. /// <returns></returns>
  37. public async Task<List<TEntity>> ExecuteAllSql(string sql, object whereObj = null)
  38. {
  39. return await Task.Run(() => Db.Ado.SqlQuery<TEntity>(sql, whereObj));
  40. }
  41. /// <summary>
  42. /// 根据ID查询一条数据
  43. /// </summary>
  44. /// <param name="objId"></param>
  45. /// <returns></returns>
  46. public async Task<TEntity> GetById(object objId)
  47. {
  48. return await Db.Queryable<TEntity>().In(objId).SingleAsync();
  49. }
  50. /// <summary>
  51. /// 根据IDs查询数据
  52. /// </summary>
  53. /// <param name="lstIds">id列表</param>
  54. /// <returns>数据实体列表</returns>
  55. public async Task<List<TEntity>> GetByIds(List<object> lstIds)
  56. {
  57. return await Db.Queryable<TEntity>().In(lstIds).ToListAsync();
  58. }
  59. /// <summary>
  60. /// 插入实体
  61. /// </summary>
  62. /// <param name="entity">实体类</param>
  63. /// <returns></returns>
  64. public async Task<int> Add(TEntity entity)
  65. {
  66. var insert = Db.Insertable(entity);
  67. return await insert.ExecuteCommandAsync();
  68. }
  69. /// <summary>
  70. /// 批量插入实体
  71. /// </summary>
  72. /// <param name="listEntity">实体集合</param>
  73. /// <returns>影响行数</returns>
  74. public async Task<int> Add(List<TEntity> listEntity)
  75. {
  76. return await Db.Insertable(listEntity.ToArray()).ExecuteCommandAsync();
  77. }
  78. /// <summary>
  79. /// 更新实体
  80. /// </summary>
  81. /// <param name="entity">实体类</param>
  82. /// <returns></returns>
  83. public async Task<bool> Update(TEntity entity)
  84. {
  85. return await Db.Updateable(entity).ExecuteCommandHasChangeAsync();
  86. }
  87. /// <summary>
  88. /// 批量更新实体
  89. /// </summary>
  90. /// <param name="listEntity">实体类</param>
  91. /// <returns></returns>
  92. public async Task<int> Update(List<TEntity> listEntity)
  93. {
  94. return await Db.Updateable(listEntity).ExecuteCommandAsync();
  95. }
  96. /// <summary>
  97. /// 根据实体删除数据
  98. /// </summary>
  99. /// <param name="entity">实体</param>
  100. /// <returns></returns>
  101. public async Task<bool> Delete(TEntity entity)
  102. {
  103. return await Db.Deleteable(entity).ExecuteCommandHasChangeAsync();
  104. }
  105. /// <summary>
  106. /// 根据实体集合批量删除数据
  107. /// </summary>
  108. /// <param name="models"></param>
  109. /// <returns></returns>
  110. public async Task<bool> Delete(List<TEntity> models)
  111. {
  112. return await Db.Deleteable(models).ExecuteCommandHasChangeAsync();
  113. }
  114. /// <summary>
  115. /// 根据ID删除数据
  116. /// </summary>
  117. /// <param name="id">ID</param>
  118. /// <returns></returns>
  119. public async Task<bool> DeleteById(object id)
  120. {
  121. return await Db.Deleteable<TEntity>(id).ExecuteCommandHasChangeAsync();
  122. }
  123. /// <summary>
  124. /// 根据IDs批量删除数据
  125. /// </summary>
  126. /// <param name="ids">ID集合</param>
  127. /// <returns></returns>
  128. public async Task<bool> DeleteByIds(List<object> ids)
  129. {
  130. return await Db.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
  131. }
  132. /// <summary>
  133. /// 根据条件查询数据是否存在
  134. /// </summary>
  135. /// <param name="whereExpression"></param>
  136. /// <returns></returns>
  137. public async Task<bool> GetAnyByFilter(Expression<Func<TEntity, bool>> whereExpression)
  138. {
  139. return await Db.Queryable<TEntity>().AnyAsync(whereExpression);
  140. }
  141. /// <summary>
  142. /// 根据条件查询一条数据
  143. /// </summary>
  144. /// <param name="whereExpression"></param>
  145. /// <returns></returns>
  146. public async Task<TEntity> GetSingleByFilter(Expression<Func<TEntity, bool>> whereExpression)
  147. {
  148. return await Db.Queryable<TEntity>().FirstAsync(whereExpression);
  149. }
  150. /// <summary>
  151. /// 查询所有数据
  152. /// </summary>
  153. /// <returns></returns>
  154. public async Task<List<TEntity>> Get()
  155. {
  156. return await Db.Queryable<TEntity>().ToListAsync();
  157. }
  158. /// <summary>
  159. /// 查询数据列表----按条件表达式
  160. /// </summary>
  161. /// <param name="whereExpression">条件表达式</param>
  162. /// <returns>数据列表</returns>
  163. public async Task<List<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression)
  164. {
  165. return await Db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
  166. }
  167. /// <summary>
  168. /// 查询数据列表----按条件表达式、排序表达式
  169. /// </summary>
  170. /// <param name="whereExpression">条件表达式</param>
  171. /// <param name="orderByExpression">排序表达式</param>
  172. /// <param name="isAsc">是否升序排序</param>
  173. /// <returns></returns>
  174. public async Task<List<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, bool isAsc = true)
  175. {
  176. return await Db.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToListAsync();
  177. }
  178. /// <summary>
  179. /// 分页查询
  180. /// </summary>
  181. /// <param name="selector"></param>
  182. /// <param name="whereExpression">条件表达式</param>
  183. /// <param name="intPageIndex">页码</param>
  184. /// <param name="intPageSize">页大小</param>
  185. /// <param name="orderDescSelector">排序字段</param>
  186. /// <returns></returns>
  187. public async Task<PaginatedViewModel<TResult>> Get<TResult>(Expression<Func<TEntity, TResult>> selector, Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, Expression<Func<TEntity, object>> orderDescSelector = null)
  188. {
  189. var query = Db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression);
  190. query = query.OrderByIF(orderDescSelector != null, orderDescSelector);
  191. var totalCount = 0;
  192. var results = query.Select(selector).ToPageList(intPageIndex, intPageSize, ref totalCount).ToList();
  193. var basePage = new PaginatedViewModel<TResult>(intPageIndex, intPageSize, totalCount, results);
  194. return await Task.FromResult(basePage);
  195. }
  196. /// <summary>
  197. /// 分页查询
  198. /// </summary>
  199. /// <param name="selector"></param>
  200. /// <param name="whereExpression">条件表达式</param>
  201. /// <param name="intPageIndex">页码</param>
  202. /// <param name="intPageSize">页大小</param>
  203. /// <param name="orderDescSelector">排序字段</param>
  204. /// <returns></returns>
  205. public async Task<PaginatedViewModel<TEntity>> Get(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, Expression<Func<TEntity, object>> orderDescSelector = null)
  206. {
  207. var query = Db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression);
  208. query = query.OrderByIF(orderDescSelector != null, orderDescSelector);
  209. var totalCount = 0;
  210. var results = query.ToPageList(intPageIndex, intPageSize, ref totalCount).ToList();
  211. var basePage = new PaginatedViewModel<TEntity>(intPageIndex, intPageSize, totalCount, results);
  212. return await Task.FromResult(basePage);
  213. }
  214. }

事务接口实现:

  1. public class UnitOfWork : IUnitOfWork, IDisposable
  2. {
  3. private readonly ISqlSugarClient _sqlSugarClient;
  4. private bool _disposed = false;
  5. public UnitOfWork(ISqlSugarClient sqlSugarClient)
  6. {
  7. _sqlSugarClient = sqlSugarClient;
  8. }
  9. public SqlSugarClient GetDbClient()
  10. {
  11. return (SqlSugarClient)_sqlSugarClient;
  12. }
  13. public void BeginTran()
  14. {
  15. GetDbClient().BeginTran();
  16. }
  17. public void CommitTran()
  18. {
  19. try
  20. {
  21. GetDbClient().CommitTran();
  22. Dispose();
  23. }
  24. catch
  25. {
  26. GetDbClient().RollbackTran();
  27. Dispose();
  28. }
  29. }
  30. public void RollbackTran()
  31. {
  32. GetDbClient().RollbackTran();
  33. Dispose();
  34. }
  35. public void Dispose()
  36. {
  37. Dispose(true);
  38. GC.SuppressFinalize(this);
  39. }
  40. public void Dispose(bool disposing)
  41. {
  42. if (_disposed) return;
  43. if (disposing)
  44. {
  45. GetDbClient()?.Dispose();
  46. }
  47. _disposed = true;
  48. }
  49. ~UnitOfWork() => Dispose(false);
  50. }

分页查询模型:

  1. public class PaginatedViewModel<T>
  2. {
  3. public int PageIndex { get; private set; }
  4. public int PageSize { get; private set; }
  5. public long Count { get; private set; }
  6. public IEnumerable<T> Data { get; private set; }
  7. public PaginatedViewModel(int pageIndex, int pageSize, long count, IEnumerable<T> data)
  8. {
  9. PageIndex = pageIndex;
  10. PageSize = pageSize;
  11. Count = count;
  12. Data = data;
  13. }
  14. }

3、SqlSugar在项目中的使用

1)、定义及初始化

  1. private readonly ISqlSugarRepository<StatEquipmentInfo> _statEquipmentInfoRepository;
  2. public GetStatusInfoHandler(ISqlSugarRepository<StatEquipmentInfo> statEquipmentInfoRepository)
  3. {
  4. _statEquipmentInfoRepository = statEquipmentInfoRepository;
  5. }

2)、使用

var infos = await _statEquipmentInfoRepository.GetSingleByFilter(s => s.EId == requestDtoModel.EId && s.StatDate == requestDtoModel.StatDate && s.ETypeId == requestDtoModel.ETypeId);
            

其他函数的使用,按照接口规范要求使用即可,在这里就不过多赘叙了。

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

闽ICP备14008679号