ASP.NET Core EF Code First appsettings.json

asp.net asp.net-core c# entity-framework entity-framework-core

Question

I'm looking for a method to switch dynamically between production and test environment.

I have two different connection strings to MSSQL databases. I want to dynamically pass this to my dbContext:

   services.AddDbContext<ViggrContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));

I have two types of publish profiles, one for Test and another for Production environment. In this profile I choose a connection to the database. Ofcourse the Test profile points to the TestDatabase connection string and the Production profile points to the Production Database. enter image description here

But how can I dynamically load the Startup.cs class in this section of the code?

   services.AddDbContext<ViggrContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));

Do you have any suggestions ?

1
1
12/8/2016 4:31:21 PM

Popular Answer

You can configure different environment connection strings in different appsettings files like this-

For test environment, use appsettings.test.json

 "Data": {
    "ViggrContext": {
      "ConnectionString": "" /*<<== TestDatabase connection string */
    },

For prod environment, use appsettings.prod.json

 "Data": {
    "ViggrContext": {
      "ConnectionString": "" /*<<== ProdDatabase connection string */
    },

Use ASPNETCORE_ENVIRONMENT environment variable to set current environment as Test or Prod values.

In Startup, you can use like this-

     services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration["Data:ViggrContext:ConnectionString"]));

See if this helps.

3
12/8/2016 5:58:34 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow