big*_*ter 3 c# entity-framework-core asp.net-core
这就是我目前在Startup.cs中的ConfigureServices方法中添加DbContext的方法:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddDbContext<MyDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
.....
}
Run Code Online (Sandbox Code Playgroud)
我的连接字符串存储在我的appsettings.json文件中,例如:
{
....
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;password=root;database=mydb;sslmode=none"
}
....
}
Run Code Online (Sandbox Code Playgroud)
如果我想切换正在连接的数据库,如果它是"开发"与"生产"环境,如何使"services.AddDbContext()"切换数据库?
您可以在不同的appsettings文件中配置不同的环境连接字符串,例如:
对于测试环境,请使用appsettings.测试 .json
"Data": {
"MyDbContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
Run Code Online (Sandbox Code Playgroud)
对于prod环境,请使用appsettings.prod .json
"Data": {
"MyContext": {
"ConnectionString": "" /*<<== ProdDatabase connection string */
},
Run Code Online (Sandbox Code Playgroud)
使用ASPNETCORE_ENVIRONMENT环境变量将当前环境设置为Test或Prod值.
在Startup中,您可以像这样使用 -
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(Configuration["Data:MyContext:ConnectionString"]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1626 次 |
| 最近记录: |