views:

188

answers:

3

What is the simplest way to programmatically toggle back and forth between test and dev databases using the LINQ to SQL ORM?

+2  A: 
using (MyDataContext dc = new MyDataContext(connectionString) )
{
  //do a unit of work.
}
David B
+7  A: 

When newing up a DataContext, one of the overloads takes a connection string. I would therefore have a compiler switch something like:

 #if Debug
 string connectionString = ....
 #else
 string connectionString = ...
 #endif

 DbDataContext db = new DbDataContext(connectionString);
BFree
I agree with this comment, although I would move the connection strings completely out of code and into either your app/web.config or another centralized configuration source.
Serapth
You still can. You can have two parts in your config file and when you assign the connection strings in code, you grab the correct one base on whether you're in debug or not.
BFree
+7  A: 

Using a connection string in the web/app config. Have multiple configs for dev/test/prod. Each should have the appropriate connection string. Switch the config for each environment.

tvanfosson
I've never liked this approach, seems like it leaves a lot of room for error.
mgroves
I have my set up with DEV as the default. That happens to be on my local machine which is unavailable from either test or prod. If the publication of the app doesn't switch out the config the app fails loudly and early.
tvanfosson
+1 this is the right answer. You should mention that you can use msbuild to replace web.config sections so ie you get your DEV conn string on a debug build, but your PROD string on a release build
Gabe Moothart
+1, I've used this approach in multiple projects and never had a problem. Personally I wish MS would remove the default constructor and force a connection string as an explicit parameter to the constructor.
confusedGeek