【问题标题】:Sql Dependency does not fireSql 依赖项不会触发
【发布时间】:2015-10-24 21:37:49
【问题描述】:

这是来自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 fireSomeMethod`。

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

【问题讨论】:

    标签: c# sql sqldependency


    【解决方案1】:

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

    OnDependencyChange会在上述命令的查询结果发生变化时触发。

    如果您查看SqlNotificationEventArgs 的参考页面,它不会告诉您哪些行发生了变化——您必须自己查询数据库才能确定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多