advanced web statistics

LINQ to SQL and Using Multiple Connection Strings

7/1/2008 2:44:23 PM

So I found something pretty interesting today in regards to LINQ and LINQ-to-SQL classes.  I was setting up a staging server to deploy a new 3.5 web application.  I then realized, "Oh crap, different connection string!".  This should be easy as all I should have to do is modify the app.config and update the connectionString accordingly. WRONG!

The connection string is actually compiled into the code. That sucks. Here's what I see in Reflector:

[SpecialSetting(SpecialSetting.ConnectionString), ApplicationScopedSetting, DebuggerNonUserCode, DefaultSettingValue("Data Source=(local);Initial Catalog=FooDB;User ID=;Password=")]
public string FooDBConnectionString
{
   get
   {
      return (string) this["FooDBConnectionString"];
   }


Gross.  I thought of a work-around that could work.  This code is in the Settings.Designer.cs class so I could do something like:

public string FooDBConnectionString
{
#if DEBUG
   get { return ((string)(this["FooDBConnectionStringDev"])); }
#else
   
get { return ((string)(this["FooDBConnectionStringProduction"])); }
#endif
}

This way the appropriate connection string could be compiled into the code depending on whether or not the configuration for the project is set to Debug or Release.  The thing about this solution is that you would have to write this code each and every time you regenerate your LINQ-to-SQL class file(s).  Very inefficient. *NOTE* For this to even work you have to add another connection string in your Settings file. No thanks.

The REAL way to solve this:

  1. Create a LINQ-to-SQL dbml file with an initial connection string
  2. Right-click dbml surface
  3. Click 'Properties'
  4. Expand the 'Connection' node
  5. Select 'None' for Connection String
  6. Select 'True' for Application Settings (don't know if this is completely necessary)
  7. Create a partial class for 'YourDataContextHere'
  8. Within this partial class create a parameterless constructor for 'YourDataContextHere'
  9. Set your base connection string accordingly a la:

public FooDB() : base(ConfigurationManager.ConnectionStrings["FooDB"].ConnectionString, mappingSource)
{
   // anything else

Just make sure you have ConnectionStrings node in your app/web configuration files and that you have the specified key in there or this won't work :D

Easy. Now you can throw a different connection string in your Business Layer's configuration file and be good to go.

Thanks to Jon Gallant and David Klein for the initial posts.

LINQ

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!