.net core webapi 6.0 中使用sqlsuger的注入

1:安装依赖包

 

2:在Progres.cs中注入

 

IConfiguration _config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

builder.Services.AddScoped(options =>
{
return new SqlSugarClient(new List<ConnectionConfig>()
{
new ConnectionConfig() {
ConnectionString = _config.GetConnectionString("SugarConnectString"),
DbType = DbType.MySql,
IsAutoCloseConnection = true
}
});
});

 

3:在appsetting.json中配置链接数据库的字符串

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SugarConnectString": "server=localhost;Database=sqlsugar4xtest;Uid=root;Pwd=123456;"
}
}

 

 

4:控制器中调用sqlsugar

/// <summary>
/// 订单
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class OrderController : ControllerBase
{

private readonly SqlSugarClient _db;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="db"></param>
public OrderController(SqlSugarClient db)
{
_db = db;
}
/// <summary>
/// 查询所有订单
/// </summary>
/// <returns></returns>
// GET: api/<OrderController>
[HttpGet]
public List<order> Get()
{

Util.Log4NetUtil.Info("hello");
Util.Log4NetUtil.Error("~~~error");
Util.Log4NetUtil.Fatal("~~~Fatal");
var result = _db.Queryable<order>().ToList();
return result;
}

posted @ 2022-09-15 19:54  .net&new  阅读(1222)  评论(0编辑  收藏  举报