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
 DataClasses1DataContext(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString);