WCF and SQL error

本文关键字:error SQL and WCF | 更新日期: 2023-09-27 18:26:04

我正在构建一个简单的WCF服务,该服务必须从SQL表返回一些数据。当我运行该项目时,我得到以下错误:

未能调用服务。可能的原因:服务脱机或无法访问;客户端配置与代理不匹配;现有代理无效。有关更多详细信息,请参阅堆栈跟踪。您可以尝试通过启动新代理、恢复到默认配置或刷新服务来恢复

如果我对所有SQL部分进行注释并发送一些静态数据,一切都会正常工作。这就是让我头疼的功能:

public Client getClient(int idClient)
{
    Client c = new Client();
    SqlConnection sql = new SqlConnection(@"Data Source=GRIGORE'SQLEXPRESS;Initial Catalog=testWCF;Integrated Security=True");
    sql.Open();
    SqlCommand cmd = new SqlCommand("Select * from Clienti where id = " + idClient);
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.Read())
    {
        c.idClient = int.Parse(dr["id"].ToString());
        c.numeClient = dr["nume"].ToString();
    }
    dr.Close();
    sql.Close();
    return c;
}

想法?

WCF and SQL error

您没有设置SqlCommand实例的Connection属性。你需要这样做:

    SqlCommand cmd = new SqlCommand("Select * from Clienti where id = " + idClient);
    cmd.Connection = sql;  // added Connection property initialization
    SqlDataReader dr = cmd.ExecuteReader();

或者你可以把它注入你的构造函数:

    SqlCommand cmd = new SqlCommand("...your query text", sql);

实际上,您的代码应该更像这样:

public Client getClient(int idClient)
{
    var c = new Client();
    using (var sql = new SqlConnection(@"Data Source=GRIGORE'SQLEXPRESS;Initial Catalog=testWCF;Integrated Security=True"))
    {
        sql.Open();
        using (var cmd = new SqlCommand("Select * from Clienti where id = " + idClient, sql))
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    c.idClient = int.Parse(dr["id"].ToString());
                    c.numeClient = dr["nume"].ToString();
                }
            }
        }
    }
    return c;
}

通过将连接、命令和读取器放置在using块中,即使抛出异常,也可以确保它们被处理掉。在这种情况下,您也不需要显式的Close调用,因为处理对象会帮您处理这些问题。