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 文章来源:https://www.toymoban.com/news/detail-839972.html
文章来源地址https://www.toymoban.com/news/detail-839972.html
到了这里,关于.net8+webapi+sqlsugar基本配置;“连接数据库过程中发生错误,检查服务器是否正常连接字符串是否正确”异常的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!