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

随声附和 提交于 2019-12-06 09:07:54

问题


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:


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"]));


来源:https://stackoverflow.com/questions/41267506/how-to-add-dbcontext-based-on-environment-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!