1、引入sqlsugar的nugat包
2、封裝一個(gè)操作類(參考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 =>
{
//單例參數(shù)配置,所有上下文生效
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、新建一個(gè)控制臺(tái)生成實(shí)體類
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調(diào)試拋異常
7、修改csproj文件中,僅適用.net 8(參考sqlsugar官方文檔)?
8、重新生成后就能正常連上數(shù)據(jù)庫了
?
9、仍然連接不上
new SqlConnection(db.CurrentConfig.ConnectionString).Open()//原生進(jìn)行測試 是否是 SqlSUgar問題
參考sqlsugar連不上sql server對應(yīng)文檔https://www.donet5.com/home/doc?masterId=1&typeId=1218?文章來源:http://www.zghlxwxcb.cn/news/detail-839972.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-839972.html
到了這里,關(guān)于.net8+webapi+sqlsugar基本配置;“連接數(shù)據(jù)庫過程中發(fā)生錯(cuò)誤,檢查服務(wù)器是否正常連接字符串是否正確”異常的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!