LINQ to SQL connectionstring(LINQ to SQL 连接字符串)
问题描述
我有一个应用程序,我希望能够为我的 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.
这篇关于LINQ to SQL 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ to SQL 连接字符串


基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01