LINQ to SQL的 - 设置连接字符串动态地根据环境变量 [英] Linq to Sql - Set connection string dynamically based on environment variable
问题描述
我需要根据环境变量对LINQ我的连接字符串设置为SQL。我将从基于环境变量的Web.config返回连接字符串的函数,但我怎么得到的LINQ to一直使用这种动态创建连接字符串(preferably,而无需每次都指定它) ?
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)?
我知道我可以指定使用构造连接字符串,但如何在使用的LinqDataSource在DataContext时的工作?
I know I can specify the connection string using the constructor, but how does that work when using the datacontext in a LinqDataSource?
推荐答案
使用:
MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);
对于使用LinqDataSource,拦截ContextCreating事件和手动创建的DataContext如上:
For a LinqDataSource, intercept the ContextCreating event and create the DataContext manually as above:
protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
{
e.ObjectInstance = new MyDataClassesDataContext (dynamicConnString);
}
从<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.contextcreating.aspx\">MSDN:
在默认情况下,LinqDataSource控件
创建的类型的一个实例
在将ContextTypeName指定
属性。 LinqDataSource控件
调用的默认构造函数
数据上下文对象来创建一个
对象的实例。有可能的
你必须使用非默认
构造函数或你必须创建一个
对象,从所述一个不同
在将ContextTypeName规定
属性。在这种情况下,必须
处理ContextCreating事件
手动创建数据上下文
对象。
By default, the LinqDataSource control creates an instance of the type that is specified in the ContextTypeName property. The LinqDataSource control calls the default constructor of the data context object to create an instance of the object. It is possible that you have to use a non-default constructor or you have to create an object that differs from the one specified in the ContextTypeName property. In that case, you must handle the ContextCreating event and manually create the data context object.
这篇关于LINQ to SQL的 - 设置连接字符串动态地根据环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!