加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – Linq to Sql – 根据环境变量动态设置连接字符串

发布时间:2020-12-15 23:24:32 所属栏目:asp.Net 来源:网络整理
导读:我需要根据环境变量将 Linq的连接字符串设置为Sql.我有一个函数,它会根据环境变量从web.config中返回连接字符串,但是如何让Linq始终使用这个“动态创建的”连接字符串(最好不需要每次都指定)? 我知道我可以使用构造函数来指定连接字符串,但是在LinqDataSour
我需要根据环境变量将 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:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读