c# - 从系统数据库 msdb 中选择时,Sql 依赖项的行为不同
问题描述
我正在将 sql 依赖项和 SignalR 用于 ASP.NET Web 应用程序中的通知任务。从普通数据库(我在 sql server 上创建的数据库)查询时,Sql 依赖项工作正常,但是当我将数据库更改为系统数据库 - msdb 时,SqlNotificationEventArgs 对象的 Type=Subscribe,Info=Invalid(表示 sql 查询无法通知),并且Source=Statement。在Application_Start()中已经启动了sql依赖,并且在msdb中启用了服务代理。msdb 是否需要不同的设置?我是否缺少一些权限?任何帮助表示赞赏。
PS
它的行为就像这个问题SqlDependency Only Fires On Subscribe中所问的那样,但我已经指定了数据库的属性,不同之处在于我使用的是 msdb。
我知道 Sql 依赖项需要一个“有效的”可通知 SQL 查询才能工作,但无法弄清楚为什么我的查询不受支持。下面是一个列表,指定查询应该是什么样子
https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms181122(v=sql.105)?redirectedfrom= MSDN
public class NotificationHub : Hub
{
[HubMethodName("fetchJobData")]
public static void FetchJobData()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
context.Clients.All.fetchJobData();
}
}
public class NotificationRepository
{
readonly string connectionString = ConfigurationManager.ConnectionStrings["msdb"].ConnectionString;
public void RegisterNotification()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(@"SELECT instance_id FROM dbo.[sysjobhistory];", connection))
//using (SqlCommand command = new SqlCommand(@"select [Comment] from dbo.[OrderComment];", connection))
{
//command.CommandType = CommandType.StoredProcedure;
Log.Logger.Debug("Executed");
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(SqlDependency_OnChange);
//Command excecutation is mandatory
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Log.Logger.Debug("Result " + String.Format("{0}", reader[0]));
}
}
}
}
}
private void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
Log.Logger.Debug("On change " + e.Type);
if (e.Type == SqlNotificationType.Change)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= SqlDependency_OnChange;
//Send notification message to client
NotificationHub.FetchJobData();
//Re-register notification
RegisterNotification();
}
}
}
解决方案
推荐阅读
- wordpress - 在特定管理员 URL 上禁用 Wordpress 插件
- c# - 为什么 Aspnet.Core 模型验证不对 Nullable 属性抛出异常?
- php - array_multisort $FILES 数组
- c - 将解决方案重定向到最新 SDK (10.0.18362) 后 WINNT.H 中的编译器错误
- c# - 在 IConfigureOptions 中获取 DatabaseContext 实例
- php - 如何在php中爆炸csv数组?
- mongodb - 使用 mongodb(spring boot) 执行搜索/查找操作时如何重命名字段?
- decorator - 在 nestjs 参数装饰器中禁用验证
- php - 如何在php中将对象转换为数组
- typescript - 如何检查打字稿中的数组列表中是否有重复项?