简体   繁体   English

在运行时更改LINQ-to-SQL连接字符串

[英]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. 我的应用程序广泛使用LINQ-to-SQL,现在要求应用程序能够在运行时切换它正在查看的数据库 - 所以基本上我希望能够选择我的连接字符串我声明它时的数据上下文。

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. 您可以使用App.config存储连接字符串,然后使用它们填充下拉框或其他内容。 Then use the selected Connection string in the constructor of your LINQ2SQL data context. 然后在LINQ2SQL数据上下文的构造函数中使用选定的Connection字符串。

App Config: App配置:

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

  </connectionStrings>

Use the ConfigurationManager class to access your connection strings. 使用ConfigurationManager类访问连接字符串。

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. 然后简单地将所选字符串作为LINQ2SQL datacontext构造函数中的第一个参数传递。

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 如果您的意思是通过切换应用程序正在查看的数据库,测试数据库和生产数据库,只需在web.config文件中使用相同的密钥创建两个连接字符串,但具有不同的连接字符串并根据需要对其中一个进行注释数据库

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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