![](/img/trans.png)
[英]SqlDependency.OnChange dependency_OnChange did not fire
[英]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.