.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();
相关推荐
Francek Chen8 小时前
【大数据存储与管理】分布式数据库HBase:03 HBase数据模型
大数据·数据库·hadoop·分布式·hdfs·hbase
小吴编程之路15 小时前
MySQL 索引核心特性深度解析:从底层原理到实操应用
数据库·mysql
~莫子16 小时前
MySQL集群技术
数据库·mysql
凤山老林16 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
就不掉头发16 小时前
Linux与数据库进阶
数据库
与衫16 小时前
Gudu SQL Omni 技术深度解析
数据库·sql
咖啡の猫17 小时前
Redis桌面客户端
数据库·redis·缓存
oradh17 小时前
Oracle 11g数据库软件和数据库静默安装
数据库·oracle
what丶k17 小时前
如何保证 Redis 与 MySQL 数据一致性?后端必备实践指南
数据库·redis·mysql
_半夏曲17 小时前
PostgreSQL 13、14、15 区别
数据库·postgresql