I am working on a .net core project, I wanted to change the connectionstring of the database in appsettings.json. I had created a duplicate database and named it originalname_fake01 and made a clone of the original database for testing.
I have also changed the database name in appsettings.developement.json. Everything seems fine but when I run the application in debug mode in visual studio. the data was being pulled from the original database rather than the changed database name in appsettings.json.
Here is my appsettings
connectionstrings
code:
Old connectionstring was
"connectionStrings": {
"MyConnectionString":
"Server=localhost;port=3306;database=mydb;user=root;password=rt123;"
}
changed connection string (new)
"connectionStrings": {
"FakeConnectionString":
"Server=localhost;port=3306;database=mydb_fake01;user=root;password=rt123;"
}
I am not able to understand why it is connecting to the old database rather than the new database even after changing the connectionstring
.
Any help would be appreciated.
If you want the development settings to override the production settings you need to use the same names and full path. Your connection string should be named MyConnectionString
, not MyConnectionString
if you want the DbContext to pick it automatically.
JSON setting files have no special meaning in .NET Core, they are just files. Every provider produces key/value pairs in the form Section1:Subsection1:Attribute1, Value
. Newer provider values override earlier values. Providers can be JSON or XML file readers, INI file readers, databases etc. In all cases, the settings are flattened to path/value pairs.
The file
"connectionStrings": {
"MyConnectionString": "Server=localhost;port=3306;database=mydb;user=root;password=rt123;"
}
Produces a value named connectionStrings:MyConnectionString
whose value is Server=localhost;port=3306;database=mydb;user=root;password=rt123;
. To override this you need to specify a setting with the same path.
The default Host builder specifies some default settings providers. From the docs, those are :
- appsettings.json.
- appsettings.{Environment}.json. = Secret Manager when the app runs in the Development environment.
- Environment variables.
- Command-line arguments.
Settings specified lower down the list override previous ones. This means that on a development machine, the connectionStrings:MyConnectionString
in appsettings.Developoment.json
overrides the element with the same name in appsettings.json
.
This also means that we can override the connection string with an environment variabl or a command-line argument, eg
dotnet run /connectionStrings:MyConnectionString Server=localhost;port=3306;database=mydb;user=root;password=rt123;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With