In this article, you will learn how to manage connection strings and use them in the application.
You will get answers to the following questions:
- What is a Connection String?
- How many ways to define and manage connection strings?
- Sample Codes
What is a Connection String?
The connection string is one kind of text string that is used to establish a connection from the application to the database server database.
The connection string is the collective information of the data source, database name, user name, and password.
How many ways to define and manage connection strings?
Following ways to declare and manage the connection strings:
- AppSettings.json
- Environment Settings
- Static Class
AppSettings.json
Using the AppSettings.json file, you can easily write a connection string.
Define Connection-String
Creating a separate object under the main json object just below Logging.
Using Connection-String
Open the HomeController.cs file and update the code.
Environment Settings
Using the environment setting, it takes more steps to configure the connection string than the appsettings.json file.
Note. You can set environment variables in two ways.
Command Window
![Connection-String-AspNet-Core-MVC-Net8]()
Edit Environment Variable Dialog box.
![Connection-String-AspNet-Core-MVC-Net8]()
Search for “environment” in the start menu.
You can add the new environment variable by clicking the NEW button.
![Connection-String-AspNet-Core-MVC-Net8]()
You can check and update the connection string in Local environment variables
To fetch the local environment variables
Note. You may get null value from above line, you have to restart the Visual Studio because visual studio read Environment Variable at startup only.
Static Class
Create a static class and static property to set the connection string.
You can use it in the following way:
Happy Coding.