Wednesday, June 15, 2011

A Simple Solution to the LINQ to SQL Connection String Problem

Sometimes geniuses do fumble.

Visual Studio is without question an engineering masterpiece. But the LINQ to SQL connection issue is really a silly mistake. Why would anyone want to compile a connection string, with password and all, into code?

Anyway, the geniuses did provide a good alternative.  The problem can be solved easily without having to modify anything generated by Visual Studio.

The DBML Designer generates a few constructor overloads for the DataClasses1DataContext class (assuming default naming). One of them takes in a, what else, connection string! So, when you instantiate your data context, just use this constructor instead. This is what I do for my particular application:

DataClasses1DataContext db = new


Anonymous said...

But how do you set it up to be portable? We have an application using LINQ and a WebConfig file. And it does not follow the webconfig properly.

I am new to this so please bear with me.....

S/360 said...

You need to include the line of code as shown above, each time you instantiate the database context, to read in the database details from web.config.