【问题标题】:SqlDependency change work only for one changeSqlDependency 更改仅适用于一项更改
【发布时间】:2016-09-30 14:19:33
【问题描述】:

我正在做一个项目,我需要监控我们的一个数据库表,对于任何新的记录插入,我需要在客户端更新相同的记录。

为此,我使用SqlDependency 订阅服务代理。还使用 SignalR 立即更新客户端。

我的问题是:我的订阅仅对一次更改有效,一旦我得到一次更新,不知道如何,我的订阅会自动删除。

这是订阅数据库以进行更改的代码:

SqlDependency.Start(connectionString);
SubScribeForAttendance();
SqlDependency.Stop(connectionString);

订阅功能:

public void SubScribeForAttendance()
{
    // We have selected the entire table as the command, so SQL Server executes this script and sees if there is a change in the result, raise the event
    string commandText = @"Select bnr,knrhex From dbo.TableName where bnr > SomeId";

    // Start the SQL Dependency
    SqlDependency.Start(connectionString);

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand(commandText, connection))
        {
            connection.Open();
            var sqlDependency = new SqlDependency(command);
            sqlDependency.OnChange += Dependency_OnBookingChange;

            // NOTE: You have to execute the command, or the notification will never fire.
            using (command.ExecuteReader())
            {
            }
        }
    }
}

【问题讨论】:

    标签: sql sql-server asp.net-mvc service-broker sqldependency


    【解决方案1】:

    每次触发通知都需要重新注册sql依赖,sql依赖只注册一个通知。

    在Dependency_OnBookingChange最后调用SubScribeForAttendance()重新注册sql依赖

    我从这个link找到了这个解决方案

    【讨论】:

    • 所以重新订阅是唯一的选择吗?我们不能注册多个更改吗?
    • 不,sql server 只注册一次更改,一旦触发它就会释放钩子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多