Posts Tagged ‘Add new tag’

Using Connection string with LINQ to SQL

Wednesday, September 3rd, 2008

When you are using LINQ to SQL the connection string to the database is automaticaly set in the properties for your dbml file. The connection string is set to the SQL server and databasse you are dragging and dropping tables, stored procedures with more from, onto your designer surface. For class libraries the connection string is set in the Settings and from web projects the connection string is set in the web.config file. This connection string is then read by the default constructor in the generated source code for LINQ. So with this way of setting connection string in LINQ, I have no longer control over the connection string. Well thats not true, the way to get LINQ to use the connection string you want is explained below.

First of all set the desinger file (.dbml) properties to following values: 

  • Connection = None (No default constructor is created)
  • Application Settings = False

Then create a partial class to the designer file and define a default constructor which read the connection string from your configuration file. See code example below.

using System.Web.Configuration;

/// <summary>
/// Partial class for the DataContext object,
/// which declares the default cstor.
/// </summary>
public partial class YourDataContext
{
    public YourDataContext() :
        base (WebConfigurationManager.ConnectionStrings[”yourKey”].ConnectionString)
    {
       OnCreated();
    }
}

Now you can dynamically configure which database you want your LINQ to access.