Foliotek Developer Blog

Using the Web.Config connection string with LINQ to SQL

When updating a project to use LINQ to SQL, I found an issue with deploying to multiple environments. Each environment (development, staging, live) had it's own database associated with this. Since I had the .dbml in another assembly, it was only reading from the app.config in the assembly it resided in. I was storing the database connection string in the web.config of the project so I thought it would be nice to just use that instead of the app.config.

The first thing I needed to do was to keep the .dbml file from reading from the app.config. After opening up the .dbml file, I opened the properties window for the file. In the properties window, there is a setting for "Connection". In the "Connection" dropdown I selected the "(None)" selection. That keeps the .dbml file from accessing the app.config for the database connection string.

Now I needed to get my MainDataContext to use the Web.Config connection string. For this I created a partial class for my MainDataContext and created a constructor that passed the connection string from the Web.Config.

public partial class MainDataContext  
{
    public MainDataContext()
    : base(System.Configuration.ConfigurationManager.ConnectionStrings["Database.connection.string.from.web.config"].ToString(), mappingSource)
    {
        OnCreated();
    }
}

Now when I deploy to different environments the .dbml file is accessing the correct database instead of the same one from the app.config.