Introduction
In this blog post, we will discuss three ways to define database connection string, get its values, and retrieve data in ASP.NET MVC core.
Details
We will just create a simple ASP.NET MVC Core web application.
For this, follow these steps in Visual Studio 2017.
- File > New > Project.
- Select ASP.NET Core Web Application.
- Set name and location
- In next screen, select Web Application (Model –>View –> Controller) Template, select "No Authentication", and click OK.
Now, add some necessary NuGet packages.
Tools - NuGet Package Manager - Package Manager Console
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer
For Entity Framework Core Tools to create a database from your EF Core model:
Run Install-Package Microsoft.EntityFrameworkCore.Tools
And for ASP.NET Core Scaffolding tools to create Controllers and Views:
If you are not already familiar with ASP.NET MVC Core web application development and have not developed even a single application, you should get a basic understanding of its development or read my blog by clicking here.
In previous versions of ASP.NET, we often used web.config for connection strings but in ASP.NET Core, we cannot use web.config for this purpose; rather, we can use other techniques or methods for it. Some of the simple methods are given below.
Method 1: Hard code connection string
The first and most basic method is to hard code the connection string into Startup.cs file as in the code below.
- //Method 1 (Hard coded connection string)
- var connection = @"Data Source=ATIQ;Initial Catalog=UserDB;Integrated Security=False;Persist Security Info=False;
- User ID=sa;Password=******";
- services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
- //Method 2 (Get connection string from appsettings.json)
- services.AddDbContext<MyDbContext>(options =>
- options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
where "DefaultConnection" is defined in appsetting.json at root directory of the application.
- {
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "ConnectionStrings": {
- "DefaultConnection": "Data Source=ATIQ;Initial Catalog=UserDB;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=www@123"
- }
- }

Join the conversation! Your thoughts help the community grow.