MSMVPS.COM
The Ultimate Destination for Blogs by Current and Former Microsoft Most Valuable Professionals.

LINQ to SQL Connectionstring in web.config

For starters, there's probably dozens of places on the web already, with a solution for this very same issue, but here's mine anyway.

The issue is this: when creating a website in ASP.NET using LINQ to SQL, you've probably guessed it would be a good idea to put the connectionstring in web.config. Especially since there's a special section for them there.

However, when you create a LINQ to SQL Databaclasses (.dbml) file and drag your tables on it, it's automatically configured to use the database you dragged the tables from.

And it's pretty easy to solve too. First, we want to get the connectionstring out of the .dbml file. To do this, open the .dbml file in the designer and change it's data-properties to match this:

image

Then, create a new partial class for the generated DataContext class with only a default constructor in it. This default constructor will pass the connectionstring from web.config to the constructor if it's base class, and you're al set:

public partial class MyDataContext{
    public MyDataContext()
        : base(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString,mappingSource)
    {
    }
}

This way, you can always regenerate your dataclasses without having to remember to change

use the right connectstring.

Have Fun!


Posted Fri, Mar 13 2009 6:38 by Stefan Kamphuis
Filed under: ,

Comments

Fanu wrote re: LINQ to SQL Connectionstring in web.config
on Wed, Apr 22 2009 4:49

This solution don't works.

Stefan Kamphuis wrote re: LINQ to SQL Connectionstring in web.config
on Wed, Apr 22 2009 5:05

Actually, it does work. If you would be a little more specific I might be able to help you out. Feel free to use the contact form too btw.

Stefan