Do you know the best place to place the connection string?

Last updated by Jack Pettit [SSW] about 2 months ago.See history

This rule has been archived
Archived Reason: Update connection string management: prefer IOptions pattern over Web.Config. Enables flexible, robust config in .NET, emphasizing dependency injection.

The best place to put the connection string is in the Web.Config file.That makes the code simple and easy to read. Look into the following code:

string cnnString = "data source=(local); integrated security=SSPI; persist security info=False; pooling=False; initial catalog=Northwind2";

Bad example - Using magic strings

and observe the following code which is simple and easy to read:

string cnnString = LinqToNorthwind.Properties.Settings.Default.NorthwindEFConnectionString;

Good example - Strongly typed connection string

private void Form1_Load(object sender, System.EventArgs e)
{
    //string connString = "data source=(local); integrated security=SSPI; persist security info=False; pooling=False; initial catalog=Northwind2";
    string cnnString = LinqToNorthwind.Properties.Settings.Default.NorthwindEFConnectionString;
    cboCity.Items.Add("London");
    cboCity.Items.Add("Madrid");
    cboCity.Items.Add("Sao Paulo");
    db = new NorthwindDataContext(cnnString);
    cboCity.SelectedIndex = 0;
}

Good example - Using strongly typed connection string

We open source. Powered by GitHub