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:
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString').
So I assume that it does not read the connection string correctly. I provide connection string to my DbContext in ConfigureServices method like this:
services.AddDbContext<GoalsContext>(options =>
options.UseNpgsql(Environment.GetEnvironmentVariable("CONNECTION_STRING")));
I also have tried to fix this by creating an implementation of IDesignTimeDbContextFactory like this:
public class GoalsContextFactory : IDesignTimeDbContextFactory<GoalsContext>
{
public GoalsContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<GoalsContext>();
optionsBuilder.UseNpgsql(Environment.GetEnvironmentVariable("CONNECTION_STRING");
return new GoalsContext(optionsBuilder.Options);
}
}
Any help would be very appreciated.
Update: 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:
[HttpGet]
public string GetConnectionString()
{
return _config["CONNECTION_STRING"];
}
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.
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.
So in short, yes connection string exists and I can even output it, but migration still fails due to the same exception.
Environment.GetEnvironmentVariable
directly. This means there's noCONNECTION_STRING
environment variable.