LINQ to SQL Connection String
Sometimes when working with LINQ to SQL the designer can act screwy and generate a bunch of connection strings in the Web.config, or build the connection string used to access the server into the binary. I am going to show a method I use to ensure that LINQ2SQL uses the correct connection string by creating a partial class with the same name as the generated data context.
First, create a new partial class in the same namespace as your LINQ2SQL DBML file. Name the class the same name as the file with "DataContext" at the end. For example, if my LINQ2SQL file is "Example.dbml" my class name will be "ExampleDataContext."
Next, add a default constructor like the one shown, replacing the constructor name and connection string key to your own values:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Linq;
namespace Example
{
partial class ExampleDataContext
{
public ExampleDataContext()
: base(ConfigurationManager.ConnectionStrings["ExampleConnectionString"].ConnectionString, mappingSource)
{
}
}
}
Now, whenever you edit your DBML file, make sure to set the "ApplicationSettings" property to false, and delete the connection string that was auto-generated.
Now your data layer will always use the correct connection string (when you use the default constructor), and the DBML designer will stop tossing in extra connection strings.