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

时间:2009-06-19 18:35:03

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

我正在尝试在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'登录失败。有任何想法吗?非常感谢。

3 个答案:

答案 0 :(得分:10)

您似乎正在尝试修改存储在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);
 } }

答案 1 :(得分:6)

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

示例:

LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);

答案 2 :(得分:4)

您可以强制DataContext使用

的特定连接字符串
DataContext db = new DataContext(myConnectionString);

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