在ASP.NET Core中,可以通过重新注册DbContext来更改连接字符串。下面是一个示例代码,演示了如何实现此功能:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
private void ReconfigureDbContext(IServiceCollection services)
{
services.RemoveDbContext();
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("NewConnection")));
}
ReconfigureDbContext(services);
请注意,此示例假设你的连接字符串已在appsettings.json文件中进行了配置,并且有一个名为"DefaultConnection"的默认连接字符串和一个名为"NewConnection"的新连接字符串。根据你的实际需求,你可能需要根据不同的情况进行修改。
重新注册DbContext后,你的DbContext将使用新的连接字符串进行数据库连接。