I’m trying to use appsettings.json
to store the database connection string to use different strings for build configurations. But, I’m getting this exception:
System.InvalidOperationException: A named connection string was used, but the name ‘ConnectionStrings:DefaultConnection’ was not found in the application’s configuration.
Here is my appsettings.json
:
"ConnectionStrings": {
"DefaultConnection": "Server=adserver\VALLOUREC;Database=eddb000;user id=devnepre;Password=nepre;MultipleActiveResultSets=False;TrustServerCertificate=True"
}
And here is how is my database context configuration:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Name=ConnectionStrings:DefaultConnection");
In program.cs
, the settings are loaded like this:
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
And I use AddDbContext
but that doesn’t change anything.
I tried some solutions suggested in this topic, but these did not work.
I know I can put the connection string directly in the OnConfiguring
function, but I don’t want to do this because every time I scaffold the database, the code is changed and I need to revert this part.
Edit: when i Scaffold the database with this command:
Scaffold-DbContext Name=ConnectionStrings:DefaultConnection Microsoft.EntityFrameworkCore.SqlServer - force
the OnConfiguring is aways replaced by this:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Name=ConnectionStrings:DefaultConnection");
i’m trying to make it works with this implementation to avoid needs to change every time o run the command.
3
Answers
Sorry, i took a while to realize that the error was not comming from my main DbContext. The project has a second Database Context that inherit the first one.
I juest need to add this code:
for this second and it's work. The inherited DbContext was not able to instance it's parent until i implement the roght constructor receiving the DbContextOptions<>
as far as I know asp.net uses .net generic host, when I did some research I found that we can get configuration values or settings through the IConfiguration interface, to do so, create a new constructor that asks for the
IConfiguration
type through parameters, assign theIConfiguration
parameter to a field and then use it as in the following code to get the data from your config file in this example itsappsettings.json
,To enable depency injection for our
ExampleDbContext
we can use the following code in our buildernote: i tried the following code in asp.net minimal api’s and it worked. i am not sure about asp.net mvc version
You should be able to use
IConfiguration
interface with registered settings from defined sources (appsettings.json
in your case).So, during registration process, you just call: