.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();
相关推荐
weixin_424999366 分钟前
PHP源码在双硬盘系统如何优化_硬件存储分配建议【指南】
jvm·数据库·python
ECT-OS-JiuHuaShan11 分钟前
渡劫代谢,好事多磨
数据库·人工智能·科技·学习·算法·生活
qq_1898070315 分钟前
json ignore反序列化?_?JSON反序列化时忽略字段的json----标签使用方法.txt
jvm·数据库·python
zhangchaoxies15 分钟前
让水平滚动条始终固定在页面底部,实现跨视口的横向滚动控制
jvm·数据库·python
justjinji23 分钟前
如何用组合继承模式实现父类方法复用与子类属性独立
jvm·数据库·python
SelectDB30 分钟前
Apache Doris 4.1:面向 AI & Search 的统一数据存储与检索底座
大数据·数据库·数据分析
djjdjdjdjjdj38 分钟前
PHP函数如何监控CPU温度传感器_PHP读取核心温度硬件值【详解】
jvm·数据库·python
m0_6138562942 分钟前
c++怎么把多个变量一次性写入二进制文件_结构体对齐与write【实战】
jvm·数据库·python
陈天伟教授1 小时前
GPT Image 2-勾股定理
大数据·数据库·人工智能·gpt
CyrusCJA1 小时前
在Windows系统上将Redis注册为系统服务使其实现开机自启
数据库·windows·redis·缓存