首页 > 数据库 >.net6 webApi IoC SqlSugar的日常使用

.net6 webApi IoC SqlSugar的日常使用

时间:2022-12-30 14:55:53浏览次数:48  
标签:webApi db SqlSugarScope master services net6 IoC public SqlSugar

.Net6 WebApi使用SqlSugar

1、Nuget先引入:SqlSugarCore

2、Net IOC

1、注入ISqlSugarClient

.NET自带的IOC使用也很方便 

先封装一个操作类

   
//建一个扩展类
public static class SqlsugarSetup
{
    public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, 
    string dbName = "db_master")
    {
        SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
        {
            DbType = SqlSugar.DbType.SqlServer,
            ConnectionString = configuration.GetConnectionString(dbName),
            IsAutoCloseConnection = true,
        },
            db =>
            {
                //单例参数配置,所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    //Console.WriteLine(sql);//输出sql
                };
                //技巧:拿到非ORM注入对象
                //services.GetService<注入对象>();
            });
        services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
    }
}
//Startup.cs或者Program 文件添加下面代码
//services.AddSqlsugarSetup(Configuration);
 

2、 Program.cs中的配置

 
builder.Services.AddSqlsugarSetup(builder.Configuration, "db_master");

 

 

 这里的db_master如果有默认值可以不写。

注意的地方:

appsettings.json 文件中一定要加 ConnectionStrings 包一下,否则会报数据库链接字符串错误。

 
 "ConnectionStrings": {
    "db_master": "Data Source=.;Initial Catalog=WApp;Persist Security Info=True;User ID=sa;Password=123456"
  }

 

3、新建一个Controller 来测试一下

   
   [Route("api/[controller]/[action]")]
    [ApiController]
    public class DbTstController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        public DbTstController(ISqlSugarClient db)
        {
            this._db = db;
        }

        [HttpGet]
        public List<SysUser> GetSysUserList()
        {
            List<SysUser> lst = _db.Queryable<SysUser>().ToList();
            return lst;
        }
    }
 

 

输出:

 

官网:https://www.donet5.com/Doc/1/2247

标签:webApi,db,SqlSugarScope,master,services,net6,IoC,public,SqlSugar
From: https://www.cnblogs.com/lhhb/p/17014880.html

相关文章