.net6 web api使用sqlsugar全局引用,mysql数据库

  1. 安装所需要的nuget包
SqlSugar
MySql.Data
  1. 在Program.cs文件全局注入sqlsugar

// 注册 SqlSugar
builder.Services.AddScoped<SqlSugarClient>(provider => new SqlSugarClient(new ConnectionConfig
{
    //ConnectionString = builder.Configuration.GetConnectionString("DbConnectionString"),
     ConnectionString = "请填入数据库连接字符串配置", //数据库连接串
    DbType = DbType.MySql,  //数据库类型
    IsAutoCloseConnection = true,
    InitKeyType = InitKeyType.Attribute // 用于支持实体类中的 [SugarColumn] 特性
}));
  1. 在控制器构造函数中使用
  public class ApiService:IApiService
    {
        private readonly SqlSugarClient _db;
        public ApiService(SqlSugarClient db)
        {
            _db = db;
        }
    }

注:下面代码是获取appsettings.json配置文件里名为“DbConnectionString”的字符串连接串

builder.Configuration.GetConnectionString("DbConnectionString")

appsettings.json文件这样写

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DbConnectionString": "Data Source=localhost;Database=imp;AllowLoadLocalInfile=true;User ID=root;Password=123456;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=3306;sslmode=none;"
  }
}

你可能感兴趣的:(数据库,.net,c#,sqlsugar,mysql)