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:
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