--- title: SqlSugar DbContext date: 2023-02-16 20:01:41 tags: SqlSugar categories: ORM description: 总结整理SqlSugar的DbContext 方便之后使用 cover: 'https://api.vvhan.com/api/acgimg' # 'https://service-dn725wcs-1306777571.gz.apigw.tencentcs.com/release/' https://api.vvhan.com/api/acgimg swiper_index: 5 # 置顶轮播图顺序,非负整数,数字越大越靠前 comments: false # 关闭评论功能 --- # **前言** {% note blue no-icon %} **什么是SqlSugar?** SqlSugar 是 .NET/C# 平台非常优秀的 ORM 框架,目前 Nuget 总下载突破 1000K,Github 关注量也高达 3.7K SqlSugar 拥有高性能,具有百万级插入、更新大数据分表等特色功能,是目前当之无愧的国产优秀 ORM 框架之一。 1. 支持 `MySql`、`SqlServer`、`Sqlite`、`Oracle`、`postgresql`、`达梦`、`人大金仓` 等多种数据库 2. 支持 `全自动分表` 3. 支持 `多库事务` 4. 支持 `CodeFirst` / `DbFirst` 5. 支持 `联表查询`、`嵌套查询`、`导航查询`、`子查询`、`动态JSON查询`等查询操作 6. 支持 SqlServer、MySql、PgSql、Oracle `百万级插入和更新` **个人感受** 其实说起来接触`SqlSugar`的时间并不是很长,但是用过之后,只有一个感觉:太丝滑了! 文档齐全,新手上路贼容易,真的{% span red, 强烈推荐 %}!!! 目前本人手里的项目,只要与数据库交互的,已经统统切换成了`SqlSugar` **官方文档** {% hideBlock 点我查看, orange %} {% link SqlSugar文档教程贴, https://www.donet5.com/Home/Doc, https://www.donet5.com/HtmlTemplate2/com_files/logo.png %} {% endhideBlock %} {% endnote %} # **.Net Framework部分** {% folding cyan, 代码 & 使用 %} >**完整代码** ```C# using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq.Expressions; using SqlSugar; using DbType = SqlSugar.DbType; namespace CodeProject.Database { /// /// 数据库上下文 /// public class SqlSugarDbContext { /// /// 数据库连接字符串(私有字段) /// private static string DbConnString = ConfigurationManager.ConnectionStrings["sqlConStr"].ConnectionString; /// /// 数据库类型(私有字段) /// private static string databaseType = ConfigurationManager.ConnectionStrings["sqlConStr"].ProviderName; /// /// 用来处理事务多表查询和复杂的操作 /// 注意:不能写成静态的 /// public SqlSugarClient Db; public SqlSugarDbContext() { DbType dbType; switch (databaseType) { case "System.Data.SqlClient": dbType = DbType.SqlServer; break; case "System.Data.SqliteClient": dbType = DbType.Sqlite; break; case "MySql.Data.MySqlClient": dbType = DbType.MySql; break; case "Oracle.ManagedDataAccess.Client": dbType = DbType.Oracle; break; default: dbType = DbType.SqlServer; break; } Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = DbConnString,//数据库连接串 DbType = dbType,//数据库类型 InitKeyType = InitKeyType.SystemTable,//从数据库中读取主键和自增列信息 //InitKeyType.Attribute,//从特性读取主键和自增列信息 IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了 }); //调式代码 用来打印SQL Db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); Console.WriteLine(); }; } #region 库表操作 /// /// 备份表 /// /// 旧表名称 /// 新表名称 /// public virtual bool BackupTable(string oldname, string newname) { if (!Db.DbMaintenance.IsAnyTable(newname, false)) { return Db.DbMaintenance.BackupTable(oldname, newname, 0); } return false; } /// /// 删除表 /// /// 表名称 /// public virtual bool DropTable(string tablename) { return Db.DbMaintenance.DropTable(tablename); } /// /// 清空表 /// /// 表名称 /// public virtual bool TruncateTable(string tablename) { return Db.DbMaintenance.TruncateTable(tablename); } #region CodeFirst 类-->表 /// /// 创建单一表 /// /// public void CreateTable(Type entityType) { Db.CodeFirst.SetStringDefaultLength(200).BackupTable().InitTables(entityType); } /// /// 批量创建表 /// /// public void CreateTables(Type[] entityTypes) { Db.CodeFirst.SetStringDefaultLength(200).BackupTable().InitTables(entityTypes); } #endregion #region DbFirst 表-->类 /// /// 根据数据库表 生成实体类文件 /// 数据库表名统一格式:XX_XXX 如:Sys_UserInfo /// /// 类文件地址 /// 命名空间 /// 表名称 public virtual void CreateClassFiles(string filePath, string nameSpace, string tableName) { #region 格式化 实体类文件名称 //循环遍历 数据库里的所有表 foreach (var item in Db.DbMaintenance.GetTableInfoList()) { string entityName = string.Empty; if (item.Name.Contains("")) { var tbName = item.Name.Split(''); entityName = tbName[1] + "Entity"; Db.MappingTables.Add(entityName, item.Name); } else { entityName = item.Name + "Entity"; Db.MappingTables.Add(entityName, item.Name); } //循环遍历 当前表的所有列 foreach (var col in Db.DbMaintenance.GetColumnInfosByTableName(item.Name)) { //所有列全部转大写 Db.MappingColumns.Add(col.DbColumnName.ToUpper(), col.DbColumnName, entityName); } } #endregion //生成指定表名的实体类文件 if (!string.IsNullOrEmpty(tableName)) { //生成带有SqlSugar特性的实体类文件 Db.DbFirst.Where(tableName).IsCreateAttribute(true).CreateClassFile(filePath, nameSpace); } //生成所有表的实体类文件 else { //生成带有SqlSugar特性的实体类文件 Db.DbFirst.IsCreateAttribute(true).CreateClassFile(filePath, nameSpace); } } #endregion #endregion #region 事务操作 /// /// 开启事务 /// public virtual void BeginTran() { Db.Ado.BeginTran(); } /// /// 提交事务 /// public virtual void CommitTran() { Db.Ado.CommitTran(); } /// /// 回滚事务 /// public virtual void RollbackTran() { Db.Ado.RollbackTran(); } #endregion #region 原生Sql /// /// 针对于 增删改 /// /// /// public virtual int ExecuteCommand(string sql, params SugarParameter[] pars) { return Db.Ado.ExecuteCommand(sql, pars); } /// /// 返回集合 /// /// /// 返回DataTable public virtual DataTable GetDataTable(string sql, params SugarParameter[] pars) { return Db.Ado.GetDataTable(sql, pars); } /// /// 返回多个集合 /// /// /// /// public virtual DataSet GetDataSet(string sql, params SugarParameter[] pars) { return Db.Ado.GetDataSetAll(sql, pars); } /// /// 调用存储过程 返回Output参数 /// /// /// /// 返回int public virtual int ExecProcToInt(string sql, params SugarParameter[] pars) { int proc_count = 0; try { BeginTran(); proc_count = Db.Ado.UseStoredProcedure().GetInt(sql, pars); CommitTran(); } catch (Exception ex) { RollbackTran(); throw ex; } return proc_count; } /// /// 调用存储过程 /// /// /// /// 返回DataTable public virtual DataTable ExecProcToDT(string sql, params SugarParameter[] pars) { DataTable dt = new DataTable(); try { BeginTran(); dt = Db.Ado.UseStoredProcedure().GetDataTable(sql, pars); CommitTran(); } catch (Exception ex) { RollbackTran(); throw ex; } return dt; } /// /// 调用存储过程 /// /// /// /// 返回DataSet public virtual DataSet ExecProcToDS(string sql, params SugarParameter[] pars) { DataSet ds = new DataSet(); try { BeginTran(); ds = Db.Ado.UseStoredProcedure().GetDataSetAll(sql, pars); CommitTran(); } catch (Exception ex) { RollbackTran(); throw ex; } return ds; } #endregion #region 泛型CURD /// /// 校验数据是否存在 /// /// Lambda表达式(查询条件) /// public virtual bool Any (Expression > expression) where TEntity : class, new() { return Db.Queryable ().Any(expression); } /// /// 检查信息总条数 /// /// Lambda表达式(查询条件) /// public virtual int Count (Expression > expression) where TEntity : class, new() { return Db.Queryable ().Count(expression); } /// /// 查询实体 /// /// /// 单条记录 public virtual TEntity FindEntity (object keyValue) where TEntity : class, new() { return Db.Queryable ().InSingle(keyValue); } /// /// 查询实体集合 /// /// public virtual ISugarQueryable Queryable () where TEntity : class, new() { return Db.Queryable (); } /// /// 自定义条件查询 /// /// Lambda表达式(查询条件) /// public virtual ISugarQueryable Queryable (Expression > expression) where TEntity : class, new() { return Db.Queryable ().Where(expression); } /// /// 通过SQL语句查询 /// /// SQL语句 /// public virtual ISugarQueryable Queryable (string strSql) where TEntity : class, new() { return Db.SqlQueryable (strSql); } /// /// 新增 /// /// 实体信息 /// public virtual int Insertable (TEntity entity) where TEntity : class, new() { return Db.Insertable(entity).ExecuteCommand(); } /// /// 批量新增 /// /// 实体信息集合 /// public virtual int Insertable (List entities) where TEntity : class, new() { return Db.Insertable(entities).ExecuteCommand(); } /// /// 编辑 /// /// 实体信息 /// public virtual int Updateable (TEntity entity) where TEntity : class, new() { return Db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); } /// /// 自定义条件编辑 /// /// /// /// public virtual int Updateable (Expression > content, Expression > predicate) where TEntity : class, new() { return Db.Updateable(content).Where(predicate).ExecuteCommand(); } /// /// 删除 /// /// 实体信息 /// public virtual int Deleteable (TEntity entity) where TEntity : class, new() { return Db.Deleteable(entity).ExecuteCommand(); } /// /// 自定义条件删除 /// /// Lambda表达式(查询条件) /// public virtual int Deleteable (Expression > expression) where TEntity : class, new() { return Db.Deleteable(expression).ExecuteCommand(); } #endregion } } ``` >**使用示例** ```C# //数据库上下文 初始化 SqlSugarDbContext db = new SqlSugarDbContext(); #region 原生Sql var dt = db.GetDataTable(strSql,pars);//返回DataTable var ds = db.GetDataSet(strSql,pars);//返回DataSet var count = db.ExcuteCommand(strSql,pars);//针对于增删改,返回受影响行数 ... #endregion #region 泛型CURD var list = db.Queryable ().ToList();//返回集合 var list = db.Queryable (expression).ToList();//返回集合 ... #endregion ... ``` {% endfolding %} # **.Net Core部分** {% folding cyan, 代码 & 使用 %} >**完整代码** ```C# ``` {% endfolding %}