Sql依赖关系不会触发

时间:2015-10-24 21:37:49

标签: c# sql sqldependency

以下是https://msdn.microsoft.com/en-us/library/62xk7953%28v=vs.110%29.aspx

的示例
void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
        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.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

如何在控制台中使用此代码设置SqlDependency。

我尝试将Initialization' method, but it does not fire SomeMethod`。

放入start方法

另外 - 如果可能的话 - 我希望将一些参数传递给我的SqlNotificationEventArgs,例如行。

1 个答案:

答案 0 :(得分:0)

Initialization方法仅打开与数据库服务器的连接。 Start方法实际上使用command注册依赖项。你的程序需要同时调用它们。

当上述命令的查询结果发生变化时,

OnDependencyChange将被触发。

如果查看SqlNotificationEventArgs的参考页面,它不会告诉您哪些行已更改 - 您必须自己查询数据库以确定该行。

相关问题