SqlDependency 仅在订阅时触发

SqlDependency Only Fires On Subscribe

我正在尝试在 SignalR 项目中使用 SqlDependancy,但我似乎无法多次触发 OnChanged 事件。它最初在订阅事件上触发,但在对基础数据库进行更改后再也不会触发。我省略了我的 SignalR 和控制器代码,因为问题似乎出在存储库 class 中。 SqlDependancy.Start() 在我的 Global.asax class.

中声明

从 SQL 服务器观察,我可以看到一个通知队列在我的应用程序启动时创建,并在我关闭时终止。

    public IEnumerable<Visitor> NotifyAllClients()
    {
        List<Visitor> visitors = new List<Visitor>();
        using (var connection = new SqlConnection(new VisitorLogEntities().Database.Connection.ConnectionString))
        {
            using (var command = new SqlCommand(@"SELECT * FROM dbo.Visitors", connection))
          //using (var command = new SqlCommand(@"SELECT [Id],[AgreeToTerms],[Base64Image],[CheckInDate],[CheckOutTime],[Company],[CountryOfOrigin],[email],[FirstName],[LastName],[IsInBuilding],[MeetingSubject],[MeetingTime],[PatriotHost],[phone],[title] FROM dbo.Visitors", connection))
            {

                var dependency = new SqlDependency(command);
                dependency.OnChange += Database_OnChange;

                if (connection.State == System.Data.ConnectionState.Closed)
                    connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                 ////compile visitor objects
                 ////visitors.add(new Visitor());
                }
            }
            return visitors.OrderByDescending(x => x.CheckInDate);
        }
    }

    private void Database_OnChange(object sender, SqlNotificationEventArgs e)
    {
        //var dependency = (SqlDependency)sender;
        //dependency.OnChange -= Database_OnChange;

        ////this fires once, with the Type of 'Subscribe', but then never fires on CRUD changes
        if (e.Type == SqlNotificationType.Change)
        {
            VisitorHub.SendVisitors();
        }
        //NotifyAllClients();
    }

编辑:上面注释掉的代码行表明需要进行更改才能使其正常工作。

从 msdn http://msdn.microsoft.com/en-US/library/a52dhwx7(v=vs.80).aspx 检查这个例子。下载VS2005_General_en-us.pdf。第 24636 页,"Using SqlDependency in a Windows Application" 是原始 link 导致的部分。请特别注意 watcher 应用程序中的第 12 步和第 13 步。在第 12 步中,您将看到 onChange 事件被删除,然后它调用第 13 步再次设置它。

此外,我认为您看到的不良行为是由于您的 sql 声明本身造成的。 sql 语句必须遵循一些规则。有关详细信息,请参阅 https://technet.microsoft.com/en-us/library/ms181122(v=sql.105).aspx。特别是编写通知查询部分。 "The statement may not use the asterisk (*) or table_name.* syntax to specify columns."