在一下代碼中,寫入數(shù)據(jù)庫地址、數(shù)據(jù)庫名、用戶名、密碼
{
"ConnectionStrings": {
"DbType": "mysql",
"Connection": "server=localhost;database=TMS;user=root;password=root"
}
}
//#region 獲取json文件里的配置
var Configuration = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var dbType = Configuration["ConnectionStrings:DbType"];
var connection = Configuration["ConnectionStrings:Connection"];
if (dbType == "sqlserver")
services.AddDbContext<DB>(options => options.UseSqlServer(connection));
else if (dbType == "mysql")
services.AddDbContext<DB>(options => options.UseMySql(connection));
上面代碼中既可以聯(lián)接mysql數(shù)據(jù)庫,也可以連接sqlserver數(shù)據(jù)庫