I have a database project that's used by other dotnet projects (azure function app and a web app). I want to use dotnet ef core cli to work with migrations, but I don't want to keep my connection string in-code (I want to my repo to be public).
Here's my current DbContext:
public ChadwickDbContext(DbContextOptions options): base(options) {}
When I run something like:
dotnet ef migrations add InitialCreate
I get the error:
Unable to create an object of type 'ChadwickDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
This worked previously because I had the connection string hard coded like this:
public ChadwickDbContext(string connectionString = "<connection string>"): base(GetOptions(connectionString)) {}
Is there any way to set the connection string via the cli or include some sort of environment file like appsettings.json
in a database-only project?
Scaffolding seems to be close to what I want, but that appears to be more of a way to generate your context and models (which is already done).
Looks like the best way to do this is to setup your own json file and register it:
Example:
public ChadwickDbContext(): base(GetOptions()) {}
private static DbContextOptions GetOptions()
{
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionString = config["ConnectionStrings:DefaultConnection"];
var options = new DbContextOptionsBuilder();
options.UseSqlServer(connectionString);
return options.Options;
}
Appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "<Connection String>"
}
}