.NET6使用SqlSugar操作数据库

1.//首先引入SqlSugarCore包
2.//新建SqlsugarSetup类

csharp 复制代码
 public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
         string dbName = "ConnectString")
        {
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
               //如果是mysql,换成SqlSugar.DbType.MySql
                DbType = SqlSugar.DbType.SqlServer,
                ConnectionString = configuration[dbName],
                IsAutoCloseConnection = true,
            },
                db =>
                {
                    //单例参数配置,所有上下文生效       
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql);//输出sql
                    };
                });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }

3.//在appsettings添加连接字符串

csharp 复制代码
  "ConnectString": "Server=.;Database=db;User=sa;Password=123456;"

4.//在Program注入SqlsugarSetup类

csharp 复制代码
builder.Services.AddSqlsugarSetup(builder.Configuration);

5.//在方法中依赖注入

csharp 复制代码
        private readonly ISqlSugarClient _SqlSugarDB;
        /// <summary>
        /// 依赖注入
        /// </summary>
        public AnsweringQuestionService(ISqlSugarClient SqlSugarDB)
        {
            _SqlSugarDB = SqlSugarDB;
        }

6.使用SqlSugar增删改查

csharp 复制代码
//查询
var a = _SqlSugarDB.Queryable<UserInfo>().ToList();
var b = _SqlSugarDB.Queryable<UserInfo>().Where(a => a.UserID == "1").ToList();
//插入
var res =_SqlSugarDB.Insertable<UserInfo>(new UserInfo() { UserName = "LiuHG", Password = "123456", Role = 1 }).ExecuteCommand();
//更新
var res =_SqlSugarDB.Updateable(new UserInfo() { Id = 1, UserName = "lhg", Role = 2, Password = "123456" }).ExecuteCommand();
//删除
var res =_SqlSugarDB.Deleteable<UserInfo>().Where(it => it.Id == 1).ExecuteCommand();
相关推荐
Knight_AL1 分钟前
MySQL 递归 CTE:WITH RECURSIVE 用法详解
android·数据库·mysql
行云&流水1 小时前
自动备份mysql数据库
数据库·mysql
IMPYLH1 小时前
HTML 的 <option> 元素
服务器·数据库·html
破芽1 小时前
mysql常用命令查询
数据库·sql·mysql
数字新视界1 小时前
动环智能监控全面提升机房管理与安全效率
数据库·物联网·数据中心·数据中心基础设施管理·dcim管理系统
程序员-Benothing1 小时前
MySQL 中的 Log Buffer 是什么?它有什么作用?
数据库·mysql·面试
rockey62710 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
倔强的石头_11 小时前
连接数失控排查:从数据库会话、应用线程池到连接池泄漏
数据库
hzxpaipai12 小时前
企业官网技术架构拆解:前端、后台、数据库、服务器如何协同
前端·数据库·架构
爱吃火鸡面呀13 小时前
MySQL DQL 子查询详解:从标量、列、行到表子查询的完整实战
大数据·数据库·mysql