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

前端之家收集整理的这篇文章主要介绍了asp.net – 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

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.

原文链接:https://www.f2er.com/aspnet/250321.html

猜你在找的asp.Net相关文章