Untie the Connection String from DataContext (LINQ to SQL)

When you work with LINQ to SQL you probably want your DataContext (and all the entities) to be in its own assembly. It’s a normal decision when developing n-tier applications.

The Problem

When you create your LINQ to SQL classes file (dbml) you have two options for your database connection string:

  1. In Settings.settngs file of the corresponding assembly
  2. Hard-coded in your DataContext desginer (.designer.cs file)

Well, when you have a web application or WinForms/WPF application you definitely would like to manage your connection string from the general config file (web.config or app.config). In this situation it would be a little pain.

The Solution

The DataContext class has a constructor, accepting a connection string as an argument. So it’ a possible solution to pass your connection string each time you create a new data context. But this solution is a little frustrating. If you create a new DataContext class 1000 times in your code, each time you’ll have to pass the connection string.

Another possible solution is to modify the designer file (.designer.cs). In the default constructor of your DataContext, modify it to pass the base constructor your connection string. And you get your connection string using the ConfigurationManager class. If you develop a web application, it will access the web.config file. If you develop WinForms/WPF application, it will access the app.config file.

However this is not a good decision, because when you change something concerning LINQ to SQL classes, the designer will regenerate its code and you will lose your changes. A far better approach is to extend your DataContext with a static method. All entity classes are partial, so they can be easily extended. Your static method will look like this:

Doesn’t it look great? Now, you can create your data context in the following manner: