.net8+webapi+sqlsugar基本配置;“连接数据库过程中发生错误,检查服务器是否正常连接字符串是否正确”异常

服务器 0

1、引入sqlsugar的nugat包

2、封装一个操作类(参考sqlsugar官方文档)

    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        }    }

3、配置program.cs和appsettings

program.cs加上下面代码

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

 appsettings配置连接字符串

4、新建一个控制台生成实体类

5、添加测试的controller

namespace Crud_demo02.Controllers{    [ApiController]    [Route("[controller]/[action]")]    public class TestController : ControllerBase    {        private readonly ISqlSugarClient _db;        public TestController(ISqlSugarClient db)        {            this._db = db;        }        [HttpGet]        public List<sys_user> GetAll()        {            bool isconnect=_db.CopyNew().Ado.IsValidConnection();            List<sys_user> lst =_db.Queryable<sys_user>().ToList();            return lst;        }    }}

6、swagger调试抛异常

7、修改csproj文件中,仅适用.net 8(参考sqlsugar官方文档) 

8、重新生成后就能正常连上数据库了

 

9、仍然连接不上

new SqlConnection(db.CurrentConfig.ConnectionString).Open()//原生进行测试 是否是 SqlSUgar问题

参考sqlsugar连不上sql server对应文档https://www.donet5.com/home/doc?masterId=1&typeId=1218 

 

也许您对下面的内容还感兴趣: