一、在appsetting.json中设置数据库连接字符串
{
"ConnectionStrings": {
"DianXinMySql": "server=localhost;port=3306;user=root;password=password;database=db_name"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
二、在Program.cs中添加如下代码
builder.Services.AddDbContext<TelecomDbContext>(options =>
options.UseMySQL(builder.Configuration.GetConnectionString("DianXinMySql")));
其他写法:
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.Build();
//IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json").Build();
builder.Services.AddDbContext<TelecomDbContext>(options =>
{
options.UseMySQL(configuration.GetConnectionString("DianXinMySql"));
});