How to add DbContext based on environment in ASP.net Core

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

Question

This is how I am currently adding my DbContext in my ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    .....

    services.AddDbContext<MyDbContext>(options =>
        options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

    .....

}

And my connection string is stored in my appsettings.json file, like this for example:

{
    ....
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;user id=root;password=root;database=mydb;sslmode=none"
  }

  ....

}

If I want to switch which database is being connected, how do I make the "services.AddDbContext()" switch the database if it is "Development" vs. "Production" environments?

1
3
12/21/2016 4:27:36 PM

Accepted Answer

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

For test environment, use appsettings.test.json

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

For prod environment, use appsettings.prod.json

 "Data": {
    "MyContext": {
      "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<MyContext>(options =>
options.UseSqlServer(Configuration["Data:MyContext:ConnectionString"]));
8
12/21/2016 4:39:14 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