我知道我可以使用构造函数指定连接字符串,但是在 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 - 根据环境变量动态设置连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-26 05:27