代码之家  ›  专栏  ›  技术社区  ›  Vinod

如何为应用程序和迁移使用单独的连接字符串?

  •  2
  • Vinod  · 技术社区  · 6 年前

    我正在尝试获取ASP。NET Core 2,EntityFramework Core 2.0应用程序已启动并运行。作为其一部分,我们还希望开始使用迁移来管理数据模型更改。

    这是我的应用程序设置。存储连接字符串的json文件。为了保持这里的简单,我让用户/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;"
    }
    

    以下是我的创业之路。cs已设置。根据我的理解,应用程序和迁移似乎都将依赖于启动时传递的相同连接字符串。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();
            }
        }
    

    只是想知道如何传递不同的连接字符串,一个纯粹用于应用程序,另一个仅用于应用迁移?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Vinod    6 年前

    发布这个问题后,我意识到,我可以利用多环境设置。 因此,对于迁移,我将有一个单独的环境,用于管理CI/CD活动。我觉得这是一个部署问题, 所以我可以简单地创建appsettings。迁移。json或类似的东西,然后后退,在应用程序和迁移中只使用一个连接字符串。还有我的创业。cs AddDbContext参数将保持不变。

    我的应用程序设置。发展json看起来像

    {
      "SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=TestAppServiceAccount; Password=xyz$123;"  
    }
    

    我的应用程序设置。迁移。json看起来像

    {
        "SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=DbChangeServiceAccount; Password=xyz$123;"
    }
    

    How to manage multiple environments in asp.net core Microsoft提供了更多详细信息。