SqlDependency.OnChange不触发

时间:2018-07-17 14:57:54

标签: c# sql-server sqldependency

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

我有一个与.mdf连接的数据库(localdb)文件,使用数据集表和SQLDataAdapter s进行了查看和编辑(无论是否重要,我都不会知道)。我正在尝试设置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表格

1 个答案:

答案 0 :(得分:0)

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