.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();
相关推荐
forestsea27 分钟前
MySQL 入门大全:数据类型
数据库·mysql
为自己_带盐1 小时前
浅聊一下数据库的索引优化
开发语言·数据库·php
gb42152871 小时前
mysql数据库中某个数据表的碎片率自己降低了,mysql数据表对碎片率有自动优化机制吗?
数据库·mysql
码观天工2 小时前
【.NET必读】RabbitMQ 4.0+重大变更!C#开发者必须掌握的6大升级要点
c#·rabbitmq·.net·mq
AI大模型顾潇2 小时前
[特殊字符] 本地大模型编程实战(29):用大语言模型LLM查询图数据库NEO4J(2)
前端·数据库·人工智能·语言模型·自然语言处理·prompt·neo4j
有时间要学习2 小时前
MySQL——数据类型&&表的约束
数据库·mysql
AI改变未来2 小时前
数据库常见故障排查
数据库
bing_1582 小时前
MongoDB 的核心概念(文档、集合、数据库、BSON)是什么?
数据库·mongodb·oracle
feilieren2 小时前
Windows 安装 Milvus
数据库·ai·milvus
kngines2 小时前
【PostgreSQL数据分析实战:从数据清洗到可视化全流程】附录-D. 扩展插件列表(PostGIS/PostgREST等)
数据库·postgresql·数据分析·pgvector·扩展插件·postgrest·向量数据