LINQ to SQL 连接字符串
- 作者: 为什么你总是让我难过
- 来源: 51数据库
- 2022-12-08
问题描述
我有一个应用程序,我希望能够为我的 LINQ to SQL 配置连接字符串.我尝试了很多不同的方法,但似乎无法让它发挥作用.我想在应用程序运行时在代码中动态执行此操作,原因是用户可以更改连接设置.
I have an application that I want to be able to configure the connection string for my LINQ to SQL. I've tried so many different ways but cannot seem to get it working. I want to do this dynamically in the code when the app is run, the reason for this is that the user can change the connection settings.
如果我从 app.config 中删除 connectionString,应用程序仍然可以正常工作(通信),这让我想知道我应该在哪里更改连接字符串?
If I delete the connectionString out of app.config the application still works OK (communicating) which makes me wonder where I should be changing the connection string?
推荐答案
我认为最好的方法是结合 Albin 和 Rup 的答案.在配置文件中有一个值,然后在运行时读取它并将其提供给上下文构造函数,如下所示:
I think that the best way to do it is a combination of Albin's and Rup's answers. Have a value in the config file, and then read it at run time and feed it to the context constructor, something like this:
WEB.CONFIG:
<appSettings> <add key="ConString" Value="The connection string" />
代码:
//read value from config
var DBConnString = System.Configuration.ConfigurationManager.AppSettings("ConString");
//open connection
var dataContext= new MyDataContext(sDBConnString)
这样你甚至可以在运行时更改连接字符串,它会在运行的程序上工作和更改.
this way you can change the connection string even at runtime and it will work and change on the running program.
- 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 包还原找不到包,没有源
