【发布时间】: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