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

后端 未结 1 1733
情书的邮戳
情书的邮戳 2021-01-06 18:15

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

public void ConfigureServices(IServiceCollection services)
{
            


        
相关标签:
1条回答
  • 2021-01-06 19:00

    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"]));
    
    0 讨论(0)
提交回复
热议问题