我需要根据环境变量将
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.