- 在appsettings.json文件中添加两个数据库连接字符串,例如:
{
"ConnectionStrings": {
"ProductionDatabase": "Data Source=prod_server;Initial Catalog=mydb;User ID=myuser;Password=mypassword",
"TestDatabase": "Data Source=test_server;Initial Catalog=mydb_test;User ID=myuser;Password=mypassword"
}
}
- 注入IConfiguration服务到Startup.cs文件的ConfigureServices方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext(options =>
{
if (env.IsDevelopment()) // 根据环境变量选择连接字符串
{
options.UseSqlServer(Configuration.GetConnectionString("TestDatabase"));
}
else
{
options.UseSqlServer(Configuration.GetConnectionString("ProductionDatabase"));
}
});
}
- 在需要使用数据库的类中注入MyDbContext:
public class MyController : ControllerBase
{
private readonly MyDbContext _db;
public MyController(MyDbContext db)
{
_db = db;
}
[HttpGet]
public async Task Get()
{
var result = await _db.MyEntities.ToListAsync();
return Ok(result);
}
}