Using the Web.Config connection string with LINQ to SQL

by Tim Banks

When updating a project to use LINQ to SQL, I found an issue with deploying to multiple environments.  Each environment (development, staging, live) had its’ 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.

??

The "Connection" setting in the .dbml Properties

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.

Tags: , , , , ,

« »

3 Responses to “Using the Web.Config connection string with LINQ to SQL”

  1. Using the Web.Config connection string with LINQ to SQL | Tim Banks Says:

    [...] can read the whole article over at http://lanitdev.wordpress.com/2010/06/11/using-the-web-config-connection-string-with-linq-to-sql/ Share and [...]

  2. Tech Tweets of the Week: iPhoning It In – Wall Street Journal (blog) | Apple Product Tips And App News Says:

    [...] Using the Web.Config connection string with LINQ to SQL « The … [...]

  3. Thanks for the info! Says:

    Thanks for the info!…

    [...]Foliotek Development Blog » Blog Archive » Using the Web.Config connection string with LINQ to SQL[...]…

Leave a Reply

NoFollow Plugin made by Web Hosting