c# - 如何让 LINQ to SQL 使用在运行时被修改的连接字符串?

标签 c# sql-server linq-to-sql ado.net app-config

我在尝试使用 Connection String Builders (ADO.NET) 时遇到了一些困难在 LINQ to SQL 中。让我向你们展示我正在尝试做的事情:

the app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="LoremIpsum"
             connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

and a snippet of the form:

ConnectionStringSettings settings = 
    ConfigurationManager.ConnectionStrings["LoremIpsum"];
if (null != settings)
{
    string connection = settings.ConnectionString;
    SqlConnectionStringBuilder builder = 
         new SqlConnectionStringBuilder(connection);

    // passwordTextBox being the control where joe the user actually 
    // enters his credentials           
    builder.Password = passwordTextBox.Text;
}

LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext();

// finally some rather anecdotic LINQ sentence here:
var foo = db.Table.Single(bar => bar.Table == whatever);

On the other hand checking the Immediate Window:

?builder.ConnectionString
"Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish"

我总是遇到异常:用户“joe”登录失败。有任何想法吗?非常感谢。

最佳答案

您似乎正在尝试修改存储在 app.config 文件中的连接字符串。当您为数据上下文使用无参数构造函数时,它会读取设计时配置的内容。

尝试将修改后的连接字符串注入(inject)到 DataContext 的构造函数中:

ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];
SqlConnectionStringBuilder builder;
LINQTOSQLDataClassDataContext db;

if (null != settings) 
{   
    string connection = settings.ConnectionString;  
    builder = new SqlConnectionStringBuilder(connection);

   // passwordTextBox being the control where joe the user actually enters his credentials

    builder.Password =passwordTextBox.Text;  
    db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
 } }

关于c# - 如何让 LINQ to SQL 使用在运行时被修改的连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1019434/

相关文章:

asp.net - 调用 DataContext.SubmitChanges() 时出现 StackOverflow 错误

c# - 何时使用 javascript 而不是创建 aspx 页面?

c# - 如何在 C# Windows 应用程序中实现 "second mouse cursor"?

sql-server - SQL Server : Clustering by timestamp; pros/cons

asp.net-mvc - 使用 ASP.NET MVC、Linq To SQL 和 StructureMap 导致 DataContext 缓存数据

c# - LINQ外连接动态OrderBy

c# - 如何发布 ajax 调用和 C# 来识别对象

c# - Pcap.net 与 Sharppcap

java - 如何使用 context.bind 绑定(bind)数据源。连接池等

.net - 用户“NT AUTHORITY\ANONYMOUS LOGON”登录失败