C# 信号器未通知数据库更改

C# 信号器未通知数据库更改,c#,signalr,sqldependency,C#,Signalr,Sqldependency,当数据库发生更改时,我需要通知Web用户 我正在使用此功能注册活动: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] void RegisterForNotifications() { string connectionString = "";

当数据库发生更改时,我需要通知Web用户

我正在使用此功能注册活动:

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
    void RegisterForNotifications()
    {
        string connectionString = "";
        using (Repositories.GestionActivosEntities db = new Repositories.GestionActivosEntities())
            connectionString = db.Database.Connection.ConnectionString;

        connectionString = "Data Source=localhost;Initial Catalog=MyDatabase;Persist Security Info=True;Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=False;";
        string sqlQuery = @"SELECT [AlertaId]
                          ,[PadreId]
                          ,[UsuarioOrigenId]
                          ,[UsuarioDestinoId]
                          ,[AlertaOrigen]
                          ,[AlertaNombre]
                          ,[AlertaMensaje]
                          ,[AlertaMotivo]
                          ,[AlertaCreadoEn]
                          ,[AlertaEnviadoMail]
                          ,[AlertaLeidoPortal]
                      FROM [dbo].[Alerta]";

        using (var sqlConnection = new SqlConnection(connectionString))
        using (var sqlCommand = new SqlCommand(sqlQuery, sqlConnection))
        {
            sqlCommand.Notification = null;
            var sqlDependency = new SqlDependency(sqlCommand);
            sqlDependency.OnChange += OnSqlDependencyChange;
            if (sqlConnection.State == ConnectionState.Closed)
                sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
        }
    }

    void OnSqlDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SqlNotification?.Invoke(sender, e);
            RegisterForNotifications();
        }
    }
调试时,此代码正确执行,但是,当我更改该表中的数据时,不会调用OnSqlDependencyChange

另一方面,我在本页有一个教程:

我使用的代码与教程相同。区别在于我正在硬编码查询和连接字符串

有一个事实引起了我的注意

在我的代码中,当sqlCommand.ExecuteOnQuery();指令时,立即调用类型为“Subscribe”的OnSqlDependencyChange事件。但是,在本教程的代码中,仅当表发生更改时才会调用该事件。在这种情况下,调用类型为“Change”的事件

数据库已启用代理


可能发生了什么?谢谢

删除信号器标记,因为您的问题根本没有到达该层。是否创建了队列并启动了SqlDependency?我希望
sqlDependency
的生命周期会更长,这样才能起作用。您能在其他地方尝试一下吗?命令一执行就超出了范围,因此我怀疑它没有足够的时间响应。@ZorgoZ我在global.asax:SqlDependency.Start(_connectionString);。我已经勾选了它正在被执行。@PeterBons你是什么意思?