这是我当前在启动中添加我的dbcontext的方式:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddDbContext<MyDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
.....
}
,我的连接字符串存储在我的appSettings.json文件中,例如:
{
....
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;password=root;database=mydb;sslmode=none"
}
....
}
如果要切换要连接哪个数据库,则如何制作" services.addddbcontext()"如果是"开发"与"生产"环境,请切换数据库?
您可以在不同的appsettings
文件中配置不同的环境连接字符串 -
对于测试环境,请使用AppSettings。测试 .json
"Data": {
"MyDbContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
对于产品环境,请使用AppSettings。 prod .json
"Data": {
"MyContext": {
"ConnectionString": "" /*<<== ProdDatabase connection string */
},
使用ASPNETCORE_ENVIRONMENT
环境变量将当前环境设置为测试或产品值。
在启动中,您可以这样使用 -
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(Configuration["Data:MyContext:ConnectionString"]));