title: Using a database connection string stored in environment variable during migrations
body: <p>I have ASP.NET Core project in which I store my PostgreSQL connection string in an environment variable. When I try to do the initial migration the project's build succeeds, but then it throws an exception: </p>
  
  <p><em>System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString').</em></p>
  
  <p>So I assume that it does not read the connection string correctly.
  I provide connection string to my DbContext in ConfigureServices method like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>services.AddDbContext&lt;GoalsContext&gt;(options =&gt;  
    options.UseNpgsql(Environment.GetEnvironmentVariable("CONNECTION_STRING")));
  </code></pre>
  
  <p>I also have tried to fix this by creating an implementation of IDesignTimeDbContextFactory like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class GoalsContextFactory : IDesignTimeDbContextFactory&lt;GoalsContext&gt;
  {
    public GoalsContext CreateDbContext(string[] args)
    {
      var optionsBuilder = new DbContextOptionsBuilder&lt;GoalsContext&gt;();
      optionsBuilder.UseNpgsql(Environment.GetEnvironmentVariable("CONNECTION_STRING");
  
      return new GoalsContext(optionsBuilder.Options);
    }
  }
  </code></pre>
  
  <p>Any help would be very appreciated.</p>
  
  <p><strong>Update:</strong>
  I have as suggested in the comments read the official documentation on Environment variables and configuration and I have checked whether the variable exists in the first place by creating a controller with one method, which returns a connection string like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>[HttpGet]
  public string GetConnectionString()
  {
    return _config["CONNECTION_STRING"];
  }
  </code></pre>
  
  <p>And correct connection string indeed shows up in the browser when I launch it, but when I tried to add initial migration to database the exception that I have already mentioned is still thrown.</p>
  
  <p>I have also tried to comment out my implementation of IDesignTimeDbContextFactory and to manually add a call to .AddEnvironmentVariables method in my Program.cs (which I read is done automatically, but I still wanted to try), but none of that had any effect - my controller still puts out connection string while Entity Framework Core's migration still does not receive it.</p>
  
  <p>So in short, yes connection string exists and I can even output it, but migration still fails due to the same exception.</p>