在申请中收听以插入数据库 table

Listen in application for insertion in database table

我有一个 SQL Server 2005 数据库,它在一个 table 中注册来自某个设备的事件。我需要在我的 C# 应用程序中捕获这些事件。

事件随时可能发生。我正在寻找有关如何管理数据库侦听/捕获数据库发送的内容的良好实践。 Whosebug 上有一些关于这些问题的主题,但没有一种方法可以在这些情况下推荐,只有一些关于如何完成的非系统建议。

所以我问一下好的做法。这些工作应该如何完成?请帮忙。

在我看来触发器可以将一些信息从 table 发送到 c# 应用程序似乎是最好的解决方案,只是我不知道是否可以安排触发器来完成这些工作。

如有任何建议,我将不胜感激 ;)

我知道在 C# 中收到 SQL table 更改通知的唯一方法是使用 SqlDependencies

示例:

private async Task RegisterSqlDependency()
    {
        if (_dependency != null)
            _dependency.OnChange -= this.OnChange;
        String query = "select MyCol from dbo.MyTable WHERE myKey = '" + _dependecyKey + "'";

        using (SqlConnection connexion = new SqlConnection("ConnexionString"))
        {
            using (SqlCommand command = new SqlCommand(query, connexion))
            {
                _dependency = new SqlDependency(command, null, 0);
                _dependency.OnChange += this.OnChange;
                await connexion.OpenAsync();
                using (SqlDataReader reader = await command.ExecuteReaderAsync())
                {
                    while (reader.Read())
                    {
                       .... GetData ....
                    }
                }
            }
        }
    }

private void OnChange(object sender, SqlNotificationEventArgs e)
    {
      .... Data has changed on table ....
      call RegisterSqlDependency() again
    }

您必须在数据库上启用 SERVICE BROKER 才能启用 SqlDepedency:

ALTER DATABASE MyDatabase SET ENABLE_BROKER with rollback immediate;