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

我正在尝试在LINQ to SQL中使用连接字符串构建器(ADO.NET)时遇到一些困难。 让我告诉大家我正在做什么:

app.config文件:

        

和forms的片段:

 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); 

另一方面,检查立即窗口

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

我总是得到一个例外:用户’joe’登录失败。 有任何想法吗? 非常感谢提前。

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

尝试将修改后的连接字符串注入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); } } 

您忘记将connectionstring发送到DataContext构造函数。

例:

 LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString); 

您可以强制DataContext使用特定的连接字符串

 DataContext db = new DataContext(myConnectionString); 

无参数DataContext构造函数将首先使用App.config文件中的连接字符串,然后使用在编译时设置的连接字符串。