Init SqlDependency并通知更改

时间:2014-12-23 12:17:53

标签: sql-server-2008 notifications messaging service-broker sqldependency

当有人更新数据库中的数据时,我需要告诉我的应用。如果我没有被误解,SqlDependancy就是我需要的。我跟着this tutorial编写了这段代码:

class dbListener
{
    public dbListener() 
    {
        Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");

        SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");
        connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");
        connection.Open();
        SomeMethod();
    }
    SqlConnection connection;
    void SomeMethod()
    {
        // Assume connection is an open SqlConnection.
        // Create a new SqlCommand object.

        //{
            using (SqlCommand command = new SqlCommand("SELECT * FROM dbo.ArchivioErogazioni", connection))
            {
                // Create a dependency and associate it with the SqlCommand.
                SqlDependency dependency = new SqlDependency(command);
                // Maintain the refence in a class member.
                // Subscribe to the SqlDependency event.
                dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
                // Execute the command.
                command.ExecuteReader();
          //  }
        }
    }
    // Handler method
 void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change) 
        { 
            // Handle the event (for example, invalidate this cache entry).
            MessageBox.Show("ikjkjkj");
            Debug.WriteLine("fkldjkfjklgjf");
            SqlDependency dependency = (SqlDependency)sender;
            dependency.OnChange -= OnDependencyChange; 
            SomeMethod();
        }
    }

    void Termination()
    {
        // Release the dependency.
        SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
    }

}

但它不起作用。我的意思是,它运行没有错误,但当我尝试测试它,从SQL Server 2008 Management Studio更新一些值时,没有任何反应。我在管理事件的函数中放了一个断点,但它只在init阶段触发。

我犯过错误吗?我怎样才能达到目标?

1 个答案:

答案 0 :(得分:4)

  

但它仅在初始阶段触发

它会触发,因为您的查询通知订阅无效。您必须检查SqlNotificationEventArgs成员。只有Change类型是变更通知,您可能会获得Subscribe类型的Statement来源。您的查询不符合C reating a Query for Notification

中描述的条件
  
      
  • 该声明不得使用星号(*)或table_name.*语法指定列。
  •