4

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?

3 Answers 3

13

Just call :

DataContext context = new DataContext ("cxstring");
Sign up to request clarification or add additional context in comments.

Comments

6

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);

Comments

1

If you mean by switching which database your application is looking at ,Test database and production database , simply you can make two connection string in your web.config file with the same key but has different connection string and comment one of them according to the desired database

<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=ProductionDB;" providerName="System.Data.SqlClient" />
<!--<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=TestDB;" providerName="System.Data.SqlClient" />-->

by comment and uncomment you can switch between the 2 databases in run time.

to choose the connection string of your context provide it with its constructor

DataContext Productioncontext = new DataContext ("MyConnectioString");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.