WCF服务中的BeginExecuteReader错误

时间:2011-12-29 11:14:07

标签: c# .net ado.net

我正在尝试在WCF服务中异步连接到数据库。但是,尽管在连接字符串中设置了“异步处理=真”,但我得到了

  带有消息System.InvalidOperationException

BeginExecuteReader: Connection property has not been initialized.

我用来连接数据库的代码是:

public void Connect()
{
   using (SqlConnection conn = new SqlConnection("Data Source=User12-PC; Initial Catalog = BMS;  User Id=sa; Password = pass; Asynchronous Processing=true"))
   {
      SqlCommand command = new SqlCommand();
      command.CommandText = "Select l.currvalue from" +
                            " advt_ctrl_pts as p inner join advt_log_in_ctrl_pts l" +
                            " on p.registerid = l.regid and p.ddcid = l.ddcid" +
                            " where p.pointid = 5156102" +
                            " order by datetime";

      command.CommandType = CommandType.Text;

      conn.Open();
      IAsyncResult result = command.BeginExecuteReader(); //This part is returning exception
      if (result.IsCompleted)
      {
         timer = new Timer(new TimerCallback(onTimerTick), command.EndExecuteReader(result), 5000, 5000);
      }
   }
}

有谁能告诉我我在做什么?

1 个答案:

答案 0 :(得分:3)

您没有为命令分配连接:

SqlCommand command = new SqlCommand();
command.Connection = conn;