SQLConnection中的参数无效

onT*_*net 2 .net c# t-sql sql-server

我有一个连接到数据库的.NET应用程序.

在我的web.config文件中我有

<connectionStrings>
    <add name="TFOUNDATION" 
         connectionString="Data Source=TAPOLCISQL01;Initial Catalog=TapolciFoundation;Persist Security Info=True;User ID=XXXX;Password=XXXXX" 
         providerName="System.Data.SqlClient"/>
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)

用户名和密码已删除.

在我的代码后面,我打开这样的连接

protected void grabData()
{
    SqlCommand cmd = new SqlCommand("SELECT FirstName FROM CauseMarketers", new SqlConnection(ConfigurationManager.ConnectionStrings["TFOUNDATION"]));
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是

"System.Data.SQLClient.SQLConnection.SQLConnection(string)"的最佳重载方法匹配具有一些无效参数.

我不确定我在这里做错了什么.

mar*_*c_s 7

您需要.ConnectionString在您获取的配置上使用该属性:

protected void grabData()
{
    // use the .ConnectionString property to get the connection string!
    string connStr = ConfigurationManager.ConnectionStrings["TFOUNDATION"].ConnectionString;

    SqlCommand cmd = new SqlCommand("SELECT FirstName FROM CauseMarketers", new SqlConnection(connStr));
}
Run Code Online (Sandbox Code Playgroud)