Linq to Sql - 根据环境变量动态设置连接字符串 [英] Linq to Sql - Set connection string dynamically based on environment variable

查看:26
本文介绍了Linq to Sql - 根据环境变量动态设置连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据环境变量将 Linq 的连接字符串设置为 Sql.我有一个函数,它会根据环境变量从 web.config 返回连接字符串,但是如何让 Linq 始终使用这个动态创建的"连接字符串(最好不必每次都指定它)?

我知道我可以使用构造函数指定连接字符串,但是在 LinqDataSource 中使用数据上下文时它是如何工作的?

解决方案

使用:

MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);

对于 LinqDataSource,拦截 ContextCreating 事件并手动创建 DataContext,如上:

protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e){e.ObjectInstance = new MyDataClassesDataContext (dynamicConnString);}

来自 MSDN:

<块引用>

默认情况下,LinqDataSource 控件创建一个类型的实例在 ContextTypeName 中指定财产.LinqDataSource 控件调用默认构造函数数据上下文对象来创建一个对象的实例.有可能的您必须使用非默认值构造函数或者你必须创建一个与一个不同的对象在 ContextTypeName 中指定财产.在这种情况下,你必须处理 ContextCreating 事件和手动创建数据上下文对象.

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

I know I can specify the connection string using the constructor, but how does that work when using the datacontext in a LinqDataSource?

解决方案

Use:

MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);

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

From MSDN:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆