为什么我的SqlDependency没有触发

Gre*_*g B 3 sql-server sql-server-2005 sqldependency

我有一个在MS SQL Server 2005上运行的数据库和一个ASP.NET 3.5 Web应用程序.

该数据库包含一个产品目录,我用它来将"页面"提供给在Web应用程序中运行的CMS.创建页面后,应用程序会缓存它们,因此我需要通知应用程序此更改,以便重新创建页面对象.

CMS使用它自己的缓存,因此不能使用SqlCacheDependency来执行此任务.

当我启动应用程序时,我确实让订阅者出现在结果中

select * from sys.dm_qn_subscriptions
Run Code Online (Sandbox Code Playgroud)

但是,只要我向表中添加一些数据,订阅者就会消失,并且OnChanged事件永远不会触发.

在我的启动代码中,我有以下内容

// Ensure the database is setup for notifications
SqlCacheDependencyAdmin.EnableNotifications(DataHelper.ConnectionString);
SqlCacheDependencyAdmin.EnableTableForNotifications(DataHelper.ConnectionString, "Category");
SqlCacheDependencyAdmin.EnableTableForNotifications(DataHelper.ConnectionString, "Product");

if (!SqlDependency.Start(DataHelper.ConnectionString, SqlDependencyQueueName))
     throw new Exception("Something went wrong");

string queueOptions = string.Format("service = {0}", SqlDependencyQueueName);
using (var connection = new SqlConnection(DataHelper.ConnectionString))
{
     connection.Open();
     using (SqlCommand command = new SqlCommand(@"SELECT [CategoryID],[Name]
                   FROM [dbo].[Category]", connection))
     {
           // Create a dependency and associate it with the SqlCommand.
           dependency = new SqlDependency(command, queueOptions, 0);

            // Subscribe to the SqlDependency event.
            dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

            command.ExecuteReader().Close();
        }
    }

// ...

void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
    Debugger.Break(); // This never hits
    this.ReloadData();
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*anu 13

检查您的数据库sys.transmission_queue.您的通知很可能会在那里,因为无法发送而保留.该transmission_status会解释为什么会这样.有关更详细的故障排除指南,请参阅对话疑难解答.

最通常的问题是由于EXECUTE AS不被孤立的数据库DBO所有权满意,并且可以通过解决基础设施的要求:

ALTER AUTHORIZATION ON DATABASE::<dbname> TO [sa];
Run Code Online (Sandbox Code Playgroud)

然而,解决方案取决于实际问题,如上所述,取决于具体情况.