Using a .NET Core console application, it is very easy to access an existing SQL Server database. Follow the below steps for that.

- CREATE TABLE [dbo].[tb_country](
- [id] [int] IDENTITY(1,1) NOT NULL,
- country] [varchar](100) NOT NULL,
- [active] [bit] NOT NULL,
- CONSTRAINT [PK_tb_country] PRIMARY KEY CLUSTERED
- (
- [id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
Let’s add some rows in the table TB_COUNTRY:
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'The United States', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Germany', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'England', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Netherlands', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Italy', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Brazil', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'South Africa', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Japan', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'South Korea', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'North Korea', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'India', 1)
- INSERT [dbo].[tb_country] ([country], [active]) VALUES (N'Russia', 1)
- CREATE PROCEDURE [dbo].[SP_COUNTRY_GET_LIST]
- AS
- BEGIN
- SELECT id
- ,country
- ,active
- FROM tb_country
- END
Now, let’s create a .NET Core Console Application.
Step 1
First, click on the File tab, go to the New, and click on "New Project".
Let us select the Console App (.NET Core).

Step 2
We are going to use NuGet to install the packages. Right-click on Project (“ConsoleApp”) and select "Manage NuGet Packages".
Click on the "Browse" tab and search for the following packages.
- Microsoft.Extensions.Configuration;
- Microsoft.Extensions.Configuration.FileExtensions;
- Microsoft.Extensions.Configuration.Json;
- System.Data.SqlClient.
We are going to install these packages one by one.

Now, we need to add the appsettings file, where it contains our connection string to access the SQL Server Database.
Right-click on Project (“ConsoleApp”), go to Add, and click on "New Item".

Now, let’s add our connection string to the database in appsetings.json.
- {
- "ConnectionStrings": {
- "Default": "Server=YOUR_SERVER;Database=mydatabase;User Id=YOUR_USER;Password=YOUR_PASSWORD;MultipleActiveResultSets=true"
- }
- }
Don’t forget, change Server, DataBase, Id and Password according you need.
This step is very important. We need copy appsetings.json to Directory where the application will run.

Step 5
Now, we will create 2 Folders ( “MODEL”“ and DAL”). After that, we will create a class named “CountryModel “ within Model folder and a class named “CountryDAL” within DAL folder.
CountryModel.cs represents our data model and CountryDAL.cs representes our data access layer.

CountryDAL.cs
- using ConsoleApp.Model;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- namespace ConsoleApp.DAL
- {
- public class CountryDAL
- {
- private string _connectionString;
- public CountryDAL(IConfiguration iconfiguration)
- {
- _connectionString = iconfiguration.GetConnectionString("Default");
- }
- public List<CountryModel> GetList()
- {
- var listCountryModel = new List<CountryModel>();
- try
- {
- using (SqlConnection con = new SqlConnection(_connectionString))
- {
- SqlCommand cmd = new SqlCommand("SP_COUNTRY_GET_LIST", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- listCountryModel.Add(new CountryModel
- {
- Id = Convert.ToInt32(rdr[0]),
- Country = rdr[1].ToString(),
- Active = Convert.ToBoolean(rdr[2])
- });
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return listCountryModel;
- }
- }
- }
CountryModel.cs
- namespace ConsoleApp.Model
- {
- public class CountryModel
- {
- public int Id { get; set; }
- public string Country { get; set; }
- public bool Active { get; set; }
- }
- }
Program.cs
- using ConsoleApp.DAL;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.IO;
- namespace ConsoleApp
- {
- class Program
- {
- private static IConfiguration _iconfiguration;
- static void Main(string[] args)
- {
- GetAppSettingsFile();
- PrintCountries();
- }
- static void GetAppSettingsFile()
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
- _iconfiguration = builder.Build();
- }
- static void PrintCountries()
- {
- var countryDAL = new CountryDAL(_iconfiguration);
- var listCountryModel = countryDAL.GetList();
- listCountryModel.ForEach(item =>
- {
- Console.WriteLine(item.Country);
- });
- Console.WriteLine("Press any key to stop.");
- Console.ReadKey();
- }
- }
- }
Now let’s start the Console Application.
Result

In this blog, we have explored how to access SQL Server DataBase in .NET Core Console Application using a settings file. It can be useful for creating automatic routines.
If you face a problem with this code, please comment below.

Mayooran NavamanyPosted Aug 19, 2022, 5:42 AM
Nice article. Thankyou For sharing
Svante TegelandPosted Jan 15, 2021, 8:58 AM
Works great! Really good with a simple "bare-bone" project like this to get started.
Daniel VanDenBoschPosted Oct 12, 2020, 8:15 AM
Can you upload your project to github? also will this method work with postgres?
Muhammad MukarramSardarPosted Jun 24, 2020, 3:18 AM
Hi, I am using the connection string { "ConnectionStrings": { "Default": "Server=.;Database=mydatabase;Integrated Security=true;Integrated Security=SSPI;MultipleActiveResultSets=true;" } } while _connectionString is empty
SenoritaPosted Apr 21, 2020, 1:31 AM
Step -2 NuGet to install the packages, when i search all mention pakage but not found so i install this pakage i am using visual studio 2017
Ger F VersteegPosted Jan 29, 2020, 4:48 PM
Hi Giovanni, a nice and clear 'lesson'. Everything works immediately.
Chittaranjan SwainPosted Sep 24, 2019, 1:48 AM
I am getting error when run the app, System.IO.FileNotFoundException: 'The configuration file 'appsettings.json' was not found and is not optional
Chittaranjan SwainPosted Sep 20, 2019, 8:27 AM
Nice article.
Lúcio JúniorPosted Aug 7, 2019, 1:51 PM
Hello there! When I run the program, it says it connected successfully with the server, but failed while trying to make the login. This is the error message: "A connection was successfully established with the server, but then an error occurred during the login process.".
omar boushikPosted Jun 26, 2019, 7:30 AM
I'm receiving an error when i compile my application (Could not parse the JSON file.Error in the line _iconfiguration = builder.Build(); in program.cs)
Sid ChildersPosted Jun 10, 2019, 2:33 PM
I'm receiving an error when I compile my application (the gist is a bit different as I'm sending data from the database to an API). The error is The ConnectionString property has not been initialized. How do I remedy this?
Laxmidhar SahooPosted May 8, 2019, 12:23 AM
Sir Thanks for good article on .net core