我正在尝试启动并运行带有 EntityFramework Core 2.0 应用程序的 ASP.NET Core 2。作为其中的一部分,还希望开始使用迁移来管理数据模型更改。
这是我的 appsettings.json 文件,我在其中存储连接字符串。为了简单起见,我将 user/pwd 保持打开状态。在实际场景中,会使用加密。主要目标是使用两个单独的连接字符串。一种用于应用程序使用,其中用户帐户 TestAppServiceAccount 将仅用于执行读/写(仅限 DML 操作)。另一个称为 DbChangeServiceAccount,用于应用迁移(DML + DDL 操作)。
{
"SqlServerMigrationsConnection": "Server=SqlServerInstance;Database=TestDb;User Id=DbChangeServiceAccount; Password=xyz$123;",
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=TestAppServiceAccount; Password=xyz$123;"
}
这是我的 Startup.cs 的设置方式。根据我的理解,看起来应用程序和迁移都将依赖于在startup.cs中传递给AddDbContext方法的相同连接字符串。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var userServiceSqlConnection = Configuration["SqlServerAppConnection"];
services.AddDbContext<UserContext>(optiopns => optiopns.UseSqlServer(userServiceSqlConnection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
只是想知道如何传递不同的连接字符串,一个纯粹用于应用程序,另一个仅用于应用迁移?
最佳答案
发布这个问题后,我意识到,我可以利用多环境设置。 因此,对于迁移,我将拥有一个单独的环境,用于管理 CI/CD 事件。我觉得这是一个部署问题, 因此,我可以简单地创建 appsettings.migrations.json 或类似的内容,然后回退到仅对应用程序和迁移使用一个连接字符串。我的 Startup.cs AddDbContext 参数将保持不变。
我的 appsettings.development.json 看起来像
{
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=TestAppServiceAccount; Password=xyz$123;"
}
我的 appsettings.migrations.json 看起来像
{
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=DbChangeServiceAccount; Password=xyz$123;"
}
How to manage multiple environments in asp.net core Microsoft 提供了更多详细信息。
关于c# - 如何为应用程序和迁移使用单独的连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637608/