首页 > 解决方案 > SqlDependency.OnChange 不会触发

问题描述

我目前正在为我的大学项目申请。数据库更改后,应用程序应通过电子邮件发送某种形式的通知。

有一个.mdf我连接到的数据库文件,(localdb)使用数据集表和 s 完成查看和编辑SQLDataAdapter(是否重要,我不知道)。我正在尝试进行设置SqlDependency,以便它在表上执行新标志检查,以便它可以发送有关带有这些标志的行的电子邮件。

问题是我无法sqlDependency.OnChange触发事件,Service Broker已启用。启动应用程序后,我开始SqlDependency,然后在我的一种方法中编辑和保存数据,SqlAdapter数据库中的数据更改(在 mdf 文件中),但没有事件触发器。我尝试了多个教程,但似乎没有一个对我有用。这是代码:

 public void StartWatching()
    {
        SqlDependency.Stop(con.ConnectionString);
        SqlDependency.Start(con.ConnectionString);
        ExecuteWatchingQuery();
    }

    private void ExecuteWatchingQuery()
    {
        using (SqlConnection connection = new SqlConnection(con.ConnectionString))
        {
            connection.Open();
            using (var command = new SqlCommand(
                "select [id], [subject] from dbo.lots", connection))
            {
                var sqlDependency = new SqlDependency(command);
                sqlDependency.OnChange += new OnChangeEventHandler(OnDatabaseChange);
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    Log_Text.AppendText("Watching... \n");
                }
                else
                {
                    Log_Text.AppendText("No rows found.");
                }
            }
        }
    }

    private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
    {[enter image description here][1]
        SqlNotificationInfo info = args.Info;
        if (SqlNotificationInfo.Insert.Equals(info)
            || SqlNotificationInfo.Update.Equals(info)
            || SqlNotificationInfo.Delete.Equals(info))
        {
            Log_Text.AppendText("Saw changes: \n");
            Watching();
        }
        ExecuteWatchingQuery();
    }

来源:http ://ts-soft.ru/blog/mssql-database-watching

[1]:https ://i.stack.imgur.com/jyBOf.png 表格

标签: c#sql-serversqldependency

解决方案


问题在于,编辑和监控都是在同一个应用程序中完成的,我不确定是否不在同一个连接上。我将应用程序分为两个(一个 - 数据库编辑,另一个 - 用于监控的控制台应用程序),并且都开始工作。


推荐阅读