c# - 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”。但是,在本教程的代码中,仅当表发生更改时才会调用该事件。在这种情况下,使用“更改”类型调用事件。
数据库已启用代理。
可能会发生什么?谢谢
解决方案
推荐阅读
- java - 在前台服务中获取当前位置
- android - 响应式图像尺寸约束布局
- excel - 将功能保存到我的用户表单后出现运行时错误 1004
- php - Symfony 4 - 两个目录中的控制器
- wpf - 如何将 WPF TabControl 标题对齐到右侧?
- docker - Docker Windows 容器因 Azure Service Fabric 崩溃
- kotlin - 从方法访问委托对象
- ios - 请求被服务委托 (PBProcessManager) 拒绝,原因是:安全
- maple - hastype(z,radical) 给出不同的结果
- dialogflow-es - 突然禁止访问