当前位置:   article > 正文

ORM C# 封装SqlSugar 操作数据库_sqlsugar 基类封装

sqlsugar 基类封装

SqlSugar 是一款 老牌 .NET 开源多库架构ORM框架(EF Core单库架构),由果糖大数据科技团队

维护和更新 ,开箱即用最易上手的.NET ORM框架 。生态圈丰富,目前开源生态仅次于EF Core,但是在需要

多库兼容的项目或产品中更加偏爱SqlSugar 

Github源码:https://github.com/donet5/SqlSugar 

Gitee源码:SqlSugar ORM: sqlsugar 是国内最受欢迎的 ORM 框架,支持.NET CORE 和 MySql、SqlServer、Sqlite、Oracle 、 postgresql、ClickHouse、GaussDB 、TDengine 、OceanBase、OpenGauss、Tidb 、达梦、人大金仓 数据库,.NET多库支持最好的ORM,支持真实的批量操作,另外还有媲美DAPPER的性能

CSDN 下载链接:

https://download.csdn.net/download/rotion135/88279938

数据库支持

关系型数据库

MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、

人大金仓(国产推荐)、神通数据库、瀚高、Access 、OceanBase

MySqlConnector、华为 GaussDB 、南大通用 GBase、MariaDB、、Tidb、

Odbc、Percona Server, Amazon Aurora、Azure Database for MySQL、PolarDB

 Google Cloud SQL for MySQL、kunDB 、自定义数据库

时序数据库

TDengine  (支持群集,缺点不支持更新,语法比较弱支持的东西少)

QuestDb(适合几十亿数据分析,模糊查询,适合单机,语法强大,自动分表存储 ,缺点不支持删除)

列式存储库Clickhouse(适用于商业智能领域(BI),缺点大小写必须和库一样,不支持事务)
即将上线

Mongodb(mongodb.entities)即将开发

Sybase、hana、FireBird、InfluxDB

litedb、

好,废话不多说,直接说说代码中该如何使用:

-------------2024.03.16 更新---------------------------------------------------

BaseDAO 增加事务方法(原有的设计事务处理上有点问题)

-----------------------------------------------------------------------------------

DAO层的封装   

BaseDAO

  1. using SqlSugar;
  2. using System;
  3. using System.Configuration;
  4. using System.Data;
  5. namespace PCZD.SQL.Library.DAO
  6. {
  7. public class BaseDAO
  8. {
  9. private string ConfigId = Guid.NewGuid().ToString();
  10. /// <summary>
  11. /// 数据库连接类型
  12. /// </summary>
  13. protected SqlSugar.DbType _defaultDBType = SqlSugar.DbType.MySql;
  14. protected string _defaultConnString = SQLGlobal.SQLConnection;
  15. /// <summary>
  16. /// 数据库
  17. /// </summary>
  18. public ISqlSugarClient DB { get; private set; }
  19. /// <summary>
  20. /// 事务对象
  21. /// </summary>
  22. public IDbTransaction DbTransaction { get; private set; }
  23. /// <summary>
  24. /// 数据库连接属性
  25. /// 用于使用事务时的连接参数传递
  26. /// </summary>
  27. public IAdo DBAdaptor
  28. {
  29. get { return DB.Ado; }
  30. }
  31. #region 默认数据库连接
  32. /// <summary>
  33. /// 使用默认的数据库类型和已知连接初始化DB
  34. /// </summary>
  35. /// <param name="dbType"></param>
  36. /// <param name="connKey"></param>
  37. public BaseDAO(IAdo ado = null)
  38. {
  39. if (ado == null)
  40. {
  41. this.DB = new SqlSugarProvider(new ConnectionConfig()
  42. {
  43. ConfigId = ConfigId,
  44. ConnectionString = _defaultConnString,
  45. DbType = _defaultDBType,
  46. IsAutoCloseConnection = true,
  47. });
  48. this.DB.Open();
  49. }
  50. else
  51. {
  52. this.DB = ado.Context;
  53. }
  54. }
  55. #endregion
  56. #region 自定义数据库连接
  57. /// <summary>
  58. /// 使用自定义数据库类型和连接字符串初始化
  59. /// <para>
  60. /// 适用于自定义数据库连接(例如业务中连接第二种数据库)
  61. /// </para>
  62. /// </summary>
  63. /// <param name="dbType"></param>
  64. /// <param name="connKey"></param>
  65. public BaseDAO(SqlSugar.DbType dbType, string connString)
  66. {
  67. _defaultDBType = dbType;
  68. _defaultConnString = connString;
  69. this.DB = new SqlSugarProvider(new ConnectionConfig()
  70. {
  71. ConfigId = ConfigId,
  72. ConnectionString = _defaultConnString,
  73. DbType = _defaultDBType,
  74. IsAutoCloseConnection = true,
  75. });
  76. this.DB.Open();
  77. }
  78. #endregion
  79. /// <summary>
  80. /// 开启事务
  81. /// </summary>
  82. /// <returns></returns>
  83. public bool BeginTran()
  84. {
  85. this.DBAdaptor.BeginTran();
  86. DbTransaction = this.DB.Ado.Transaction;
  87. return this.DBAdaptor.IsAnyTran();
  88. }
  89. /// <summary>
  90. /// 提交事务
  91. /// </summary>
  92. /// <returns></returns>
  93. public bool CommitTran()
  94. {
  95. DbTransaction?.Commit();
  96. return true;
  97. }
  98. /// <summary>
  99. /// 事务回滚
  100. /// </summary>
  101. /// <returns></returns>
  102. public bool RollbackTran()
  103. {
  104. DbTransaction?.Rollback();
  105. return true;
  106. }
  107. }
  108. }

增删查改的操作,以ConfigDAO为例子:

  1. /// <summary>
  2. /// 系统配置数据
  3. /// </summary>
  4. public class ConfigDAO : BaseDAO
  5. {
  6. public ConfigDAO(IAdo ado = null) : base(ado) { }
  7. /// <summary>
  8. /// 查询所有的配置数据
  9. /// </summary>
  10. /// <returns></returns>
  11. public IEnumerable<t_sys_config> GetAllConfig()
  12. {
  13. var sql = base.DB.Queryable<t_sys_config>();
  14. return sql.ToList();
  15. }
  16. /// <summary>
  17. /// 获取配置数据列表
  18. /// </summary>
  19. /// <param name="parent">父节点编码,默认根节点root</param>
  20. /// <param name="cfgCode">配置项编码</param>
  21. /// <returns></returns>
  22. public IEnumerable<t_sys_config> GetConfigList(string parent, string cfgCode="")
  23. {
  24. if (string.IsNullOrEmpty(parent))
  25. {
  26. //父节点为空时,默认取根节点数据
  27. parent = "root";
  28. }
  29. var sql = base.DB.Queryable<t_sys_config>();
  30. sql = sql.Where(t => t.ParentCode == parent);
  31. if (!string.IsNullOrEmpty(cfgCode))
  32. {
  33. sql = sql.Where(t => t.CfgCode == cfgCode);
  34. }
  35. return sql.ToList();
  36. }
  37. /// <summary>
  38. /// 获取配置信息
  39. /// </summary>
  40. /// <param name="cfgCode">配置编码</param>
  41. /// <returns></returns>
  42. public t_sys_config GetConfig(string cfgCode)
  43. {
  44. var sql = base.DB.Queryable<t_sys_config>().Where(t => t.CfgCode == cfgCode);
  45. return sql.Single();
  46. }
  47. /// <summary>
  48. /// 新增前检测 true-正常,可新增 false-已存在相同数据
  49. /// </summary>
  50. /// <param name="cfgCode">配置编码</param>
  51. /// <returns></returns>
  52. public BaseResult CheckBeforeInsert(string cfgCode)
  53. {
  54. var sql = base.DB.Queryable<t_sys_config>().Where(t => t.CfgCode == cfgCode);
  55. return sql.Count() <= 0;
  56. }
  57. /// <summary>
  58. /// 新增配置数据
  59. /// 正常系统中不进行使用,配置需要脚本初始化
  60. /// </summary>
  61. /// <param name="entity">配置数据</param>
  62. /// <returns></returns>
  63. public BaseResult Insert(t_sys_config entity)
  64. {
  65. var sql = base.DB.Insertable(entity);
  66. return sql.ExecuteCommand() > 0;
  67. }
  68. /// <summary>
  69. /// 修改配置数据
  70. /// </summary>
  71. /// <param name="entity"></param>
  72. /// <returns></returns>
  73. public BaseResult Update(t_sys_config entity)
  74. {
  75. var sql = base.DB.Updateable(entity).Where(x => x.CfgCode == entity.CfgCode);
  76. return sql.ExecuteCommand() > 0;
  77. }
  78. }

事务处理:

  1. UserUgDAO dao = new UserUgDAO();
  2. try
  3. {
  4. DateTime now = DateTime.Now;
  5. string targetUser = models[0].UserCode;
  6. var dataList = dao.GetUserUgList(targetUser);
  7. List<t_userug> addList = new List<t_userug>();
  8. List<t_userug> delList = new List<t_userug>();
  9. //从源数据及目标数据中,筛选出需要新增及删除的数据
  10. delList = (from userug in dataList
  11. where !(
  12. from left in dataList join right in models on left.GroupCode equals right.GroupCode select left
  13. ).Contains(userug)
  14. select userug).ToList();
  15. addList = (from ug in models
  16. where !(
  17. from left in models join right in dataList on left.GroupCode equals right.GroupCode select left
  18. ).Contains(ug)
  19. select new t_userug()
  20. {
  21. ID = base.GetGuid(),
  22. UserCode = ug.UserCode,
  23. GroupCode = ug.GroupCode,
  24. Description = "",
  25. CreateTime = now,
  26. CreateUserCode = userCode,
  27. }
  28. ).ToList();
  29. BaseResult res = BaseResult.Successed;
  30. //开启事务
  31. dao.BeginTran();
  32. if (delList != null && delList.Count > 0)
  33. {
  34. res = dao.DeleteBatch(delList);
  35. if (!res)
  36. {
  37. //事务回滚
  38. dao.RollbackTran();
  39. return res;
  40. }
  41. }
  42. if (addList != null && addList.Count > 0)
  43. {
  44. res = dao.InsertBatch(addList);
  45. if (!res)
  46. {
  47. //事务回滚
  48. dao.RollbackTran();
  49. return res;
  50. }
  51. }
  52. //刷新来自用户组的角色继承
  53. res = RefreshUserRoleByUG(addList, delList, targetUser, userCode, dao.DBAdaptor);
  54. if (!res)
  55. {
  56. //事务回滚
  57. dao.RollbackTran();
  58. return res;
  59. }
  60. //提交事务
  61. dao.CommitTran();
  62. return BaseResult.Successed;
  63. }
  64. catch (Exception ex)
  65. {
  66. ApiLog.Error("ModifyUserUg 异常", ex);
  67. dao.RollbackTran();
  68. return new BaseResult(false, Language("Edit_Failure") + ex.Message);
  69. }

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

闽ICP备14008679号