我在尝试在linq to sql中使用Connection String Builders (ADO.NET)时遇到了一些困难。让我告诉你们我在做什么:
app.config文件:

<?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>

还有一小段表格:
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);
 } }

07-27 23:11