不支持关键字:“数据源”。在 MVC 中

Keyword not supported: '"data source'. in MVC

我运行遇到这个错误

([ArgumentException: Keyword not supported: ''data source'.])

在我的 MVC 应用程序中,我尝试在不使用 EF 的情况下在我的控制器中 运行 标准 SQL 查询。我读过其他关于转义引号的文章,但到目前为止没有任何用处。我的连接代码如下:

userDataQry = -->Long SQL Query contained in this variable <---;
connString ="\"Data Source = data.testdomain.com; Initial Catalog = DashboardData; IntegratedSecurity = True; Application Name = DMetricsApp; \"providerName=\"System.Data.SqlClient\""; 

C# Sql 连接代码:

using(SqlConnection conn = new SqlConnection(connString))
{
    using(SqlCommand objCommand = new SqlCommand(userDataQry, conn))
    {
        objCommand.CommandType = CommandType.Text;
        DataTable dt = new DataTable();
        SqlDataAdapter sdp = new SqlDataAdapter(objCommand);
        conn.Open();
        sdp.Fill(dt);

        if (dt != null)
        {
            list = dt.AsEnumerable().ToList();
        }//End if
    }//End using
}//End using

不要在连接字符串的开头和结尾放置双引号

connString =@"Data Source=data.testdomain.com;
              Initial Catalog=DashboardData;
              IntegratedSecurity = True; 
              Application Name = DMetricsApp;";

同时删除提供商名称部分。在System.Data.SqlClient

中使用类时不需要

当您传递连接字符串时,它基本上是 shorthand SqlConnectionStringBuilder class 将创建的内容;但是可能会出现问题,因为当您使用 @ 作为字符串文字

你总是可以通过艰难的方式做到这一点:

string connstring = (new SqlConnectionStringBuilder() {
    DataSource = "data.testdomain.com;"
    , InitialCatalog = "DashboardData"
    , IntegratedSecurity = true
    , ApplicationName = "DMetricsApp"
    }).ToString();