.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();
相关推荐
徐子元竟然被占了!!8 小时前
Linux-systemctl
linux·数据库·oracle
YJlio10 小时前
Active Directory 工具学习笔记(10.8):AdInsight——保存与导出(证据留存、共享与二次分析)
数据库·笔记·学习
suoyue_zhan10 小时前
GBase的管理监控平台GEM实践指南
数据库
哈哈老师啊11 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
小小8程序员11 小时前
Redis-10
数据库·redis·缓存
liuzhilongDBA11 小时前
从collation mismatch异常到其原理
数据库·version·glibc·postgres·collation
梁萌11 小时前
MySQL数据库分库分表介绍
数据库·mysql·shardingsphere·分库分表
占疏13 小时前
dify API访问工作流/聊天
开发语言·数据库·python
Cat God 00713 小时前
SQL使用及注意事项
数据库·sql·mysql