LINQ to SQL 连接字符串

时间:2023-02-18
本文介绍了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 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:您能否说服 DataContext 将列视为总是脏的? 下一篇:Linq-to-SQL 超时

相关文章

最新文章