Reputation: 206
How to configure a C# program with a connection string in Visual Studio Code?
This is for .Net Core 2.2 using .Net Core SDK version 2.2.203 in Visual Studio Code 1.34.0
I have tried to add App.Config file to the project, but I'm not able to resolve this issue. Do let me know any solution to configure connection string.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections.Specialized;
using Dapper;
namespace Sample_Dapper
{
class Program
{
static void Main(string[] args)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var SqlString = "SELECT TOP 100 [CustomerID],[CustomerFirstName],
[CustomerLastName],[IsActive] FROM [Customer]";
var ourCustomers = (List<Customer>)db.Query<Customer>(SqlString);
}
}
}
Upvotes: 4
Views: 12152
Reputation: 554
Install Microsoft.Extensions.Configuration.Json
Then add appsettings.json file to project and right click on file -properties and select copy to output as copy if newer
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
Console.WriteLine(configuration.GetConnectionString("Test"));
Console.WriteLine(configuration.GetSection("SampleObj:AnyPropName").Value);
sample appsetting.json file
{
"SampleObj": {
"AnyPropName" : "testProp"
} ,
"ConnectionStrings": {
"Test": "CONNECTION-STRING"
}
}
Upvotes: 4
Reputation: 4906
Your code has ConfigurationManager.ConnectionStrings
to get the connection string. This code will not work in .NET Core 2.2 and later, because ConfigurationManager.ConnectionStrings
is used to get connection strings in web.config for ASP.NET project and app.config for console and Winforms/WPF projects if your app is using .NET Framework.
In .NET Core 2.0 and later, most configuration is stored as JSON file, and by default the equivalent of web.config/app.config is appsettings.json
file, and you can also have your own configuration file as well, because it is highly extensible.
The official .NET Core 2.0 (or later) documentation on how to manage configuration files is available at: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
Upvotes: 2