簡體   English   中英

SqlDependency.OnChange不觸發

[英]SqlDependency.OnChange doesn't fire

我目前正在為我的大學項目提出申請。 應用程序應在數據庫更改后通過電子郵件發送某種形式的通知。

我連接到數據庫的.mdf文件(localdb) ,使用數據集表和SQLDataAdapter進行查看和編輯(localdb)是否重要,我都不知道)。 我正在嘗試設置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表格

問題是,事實上,編輯和監視都是在同一個應用程序中完成的,我不確定是否不在同一連接上。 我將應用程序分為兩部分(一個-數據庫編輯,另一個-用於監視的控制台應用程序),所有這些都開始工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM