WCF和SQL错误

seb*_*ibu 3 c# sql wcf

我正在构建一个简单的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;
}
Run Code Online (Sandbox Code Playgroud)

想法?

小智 6

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

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

或者你可以将它注入到构造函数中:

    SqlCommand cmd = new SqlCommand("...your query text", sql);
Run Code Online (Sandbox Code Playgroud)