Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing LINQ-to-SQL connection string at runtime

An application of mine uses LINQ-to-SQL extensively, and it is now a requirement of the application to be able to switch which database it is looking at at runtime - so essentially I would like to be able to choose the connection string of my data context when I declare it.

Is there an easy way of doing this?

like image 651
Chris Avatar asked Dec 01 '22 07:12

Chris


2 Answers

Just call :

DataContext context = new DataContext ("cxstring");
like image 163
Incognito Avatar answered Dec 06 '22 11:12

Incognito


You could use an App.config to store your Connection Strings then use them to populate a drop down box or something. Then use the selected Connection string in the constructor of your LINQ2SQL data context.

App Config:

<configuration>
  <connectionStrings>
    <add key="ConString1" connectionString="ConnectionStringGoesHere"/>
    <add key="ConString2" connectionString="ConnectionStringGoesHere"/>

  </connectionStrings>

Use the ConfigurationManager class to access your connection strings.

string conString = ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;

You can also enumerate over them or set them as datasource to populate a drop down box.

Then simply pass the selected string in as the first parameter in your LINQ2SQL datacontext constructor.

MyModelDataContext context = new MyModelDataContext(selectedConString);
like image 30
MarkB29 Avatar answered Dec 06 '22 09:12

MarkB29