问题
After bashing my head against a wall for the next few hours I've slowly started to realise where my problem lays, so let me give you a recap: I'm trying to change a website's string when a row gets inserted into a database, but for some reason the trigger I've made that tells me when there's been a change into the database doesn't fire at all when an insertion, udpate or whatever happens. The table's Service Broker is on.
This is the involved code:
namespace WebApplication.SignalR_Data
{
public class NotificationRepository
{
public NotificationInfo GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReservationDbContext"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT COUNT(*) FROM dbo.Reservations", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
return new NotificationInfo { RowCount = (int)command.ExecuteScalar(), Date = DateTime.Now };
}
}
}
// This is the method that handles the trigger.
public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NotificationHub.Show();
}
}
}
}
I suppose that it's not working because of mistakes I've made, but sadly I haven't been able to spot them yet.
Through NotificationHub.Show(); a message is broadcasted to all clients of the website with the updated rowcount and date, but that message is never sent because the trigger doesn't fire. Any ideas?
Thank you in advance!
回答1:
You need to register method GetData() again for continue receive event. Like this:
public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NotificationHub.Show();
}
GetData();
}
来源:https://stackoverflow.com/questions/28401057/sqldependency-doesnt-fire-on-row-insertion-or-update-or-delete