首页 > 解决方案 > SignalR 未通知数据库更改

问题描述

当数据库发生更改时,我需要通知 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。

另一方面,我在这个页面上有一个教程:https ://www.codeproject.com/Tips/1075852/ASP-NET-MVC-SignalR-SqlDependency-and-EntityFramew?msg=5672753#xx5672753xx

我使用的代码与教程相同。不同之处在于我对查询和连接字符串进行了硬编码。

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

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

数据库已启用代理。

可能会发生什么?谢谢

标签: c#signalrsqldependency

解决方案


推荐阅读