c# - 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 表格
解决方案
问题在于,编辑和监控都是在同一个应用程序中完成的,我不确定是否不在同一个连接上。我将应用程序分为两个(一个 - 数据库编辑,另一个 - 用于监控的控制台应用程序),并且都开始工作。
推荐阅读
- sql-server - BCP 是否创建目标对象?
- javascript - 如何在 Angular 5 中添加图像?
- .net - 使用 Xamarin Forms 和 MVVM 在 Entry 控件中键入字符时,在短暂延迟后请求数据
- microsoft-teams - 如何本地化我的 Microsoft Teams 机器人欢迎消息?
- javascript - 将 XML 解析为表格适用于除 IE 之外的所有浏览器
- java - 使用 GoogleAuthProvider 重新对用户进行身份验证不起作用
- swiftui - 更改为 @EnvironmentObject 中的 @Published var 不会立即反映
- javascript - 从对象数组中获取特定值 [{"key":"value"}, {"key":"value"}]
- javascript - 为什么我的砖石代码行不起作用?
- html - 如何使用node.js将数据从html发送到three.js?