简体   繁体   中英

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?

只需致电:

DataContext context = new DataContext ("cxstring");

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM