Note: If you are subscribed to our blog for house related content, and would prefer not to read nerd-speak, change your RSS subscription to: http://www.shaneandcasey.com/category/house/feed/
I’ve been looking for a clean solution to having a dynamic connection string for a LINQ to SQL data context. My primary desire for this is developing/debugging an application on a test database. Sure, you can always go change your connection string in the app.config file, but I tend to forget to revert it back before deployment.
After doing a bit of research today, I realized that if you open up the project’s property pages, click on the settings tab, and then click on ‘View Code’ on the top, you’ll access the “base” partial Settings class. In the constructor, add an event handler for the SettingsLoaded event handler:
this.SettingsLoaded += new System.Configuration.SettingsLoadedEventHandler(Settings_SettingsLoaded);
Then you can set up the event handler in a similar manner:
///
/// Dynamically update settings for development when a debugger is attached
///
void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// Adjust the connection string as you see fit
this["yourConnectionStringName"] = "Data Source=yourDevHost;Initial Catalog=yourDevDatabase;Persist Security Info=True;User ID=yourDevUser;Password=yourDevPassword";
}
}