Alex Rivera | Logout

Linq to Sql - Set connection string dynamically based on environment variable

Asked 2009-07-27T15:49:44.923
13

I need to set my connection string for Linq to Sql based on an environment variable. I have a function which will return the connection string from the web.config based on the environment variable, but how do I get Linq to always use this "dynamically created" connection string (preferably without having to specify it every time)?

I know I can specify the connection string using the constructor, but how does that work when using the datacontext in a LinqDataSource?

Edit
Report

1 Answer

6
  • Open up the LINQ to SQL designer, and open the Properties tab of the designer (the schema itself), expand Connection and set Application Settings to False. Save.

  • Close that down and open up your DataContext designer file (dbml_name.designer.cs) and alter the DataContext constructor. You will immediately notice how your connection string decided to jump in here as you turned off application wide settings. So the part to focus on here is altering the base() inheritor. Renaming ConnString” below to suit your own. I also noticed a DatabaseAttribute on the class which I don’t think plays a big part and has any implications on the connection settings. You will also need a reference to System.Configuration:

    public dbDataContext() : base(ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString, mappingSource)

  • Open the App.config or Web.config featured in the project where your LINQ to SQL classes reside, and rename the connection string to what you defined as “MyConnString“.

  • You now must Cut the entire entry with name change and Paste it into either the App.config or Web.config of the application which is to access the data, such as a web application, Silverlight, WPF, WCF etc. It is important that you alter the configuration file of the calling application which is to access the data, as the ConfigurationManager defined in your LINQ to SQL classes will look for the .config file from where the calling application is executing from, no matter where your LINQ to SQL classes have been Defined. As you can see, it works a little differently from before.

  • Now Right Click and open the Properties on your DAL or project containing your LINQ to SQL classes and remove the connection strin

answered 2011-04-13T07:08:19.057

Your Answer