Linq to Sql - 根据环境变量动态设置连接字符串
- 作者: 不吃鱼的丶喵
- 来源: 51数据库
- 2022-12-08
问题描述
我需要根据环境变量将 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
