asp.net - 如何使用 SQL Dependency 知道数据库发生的更改类型
问题描述
我有以下代码,它使用 SignalR 显示即时生命数据。一旦插入更新或删除行,表格就会使用 Signal 立即更新。但是,我特别想知道数据库发生的类型更改,无论是更新删除还是插入。我了解 onchange 方法检测到数据库上的更改,但我如何确定此更改
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionCustomer"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [Id],[CustomerName] FROM [CustomerInfoes] ", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
Id = (int)x["Id"],
CustomerName = (string)x["CustomerName"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CustomerHub.Show();
}
中心:
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>();
context.Clients.All.displayCustomer();
}
看法
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var cus = $.connection.customerHub;
// Declare a function on the job hub so the server can invoke it
cus.client.displayCustomer = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblInfo');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
'<tr>' +
'<td>' + model.Id + '</td>' +
'<td>' + model.CustomerName + '</td>' +
'<tr>'
);
});
}
});
}</script>
解决方案
您可以通过查看 eventArgs.Info属性轻松找出更改类型。
推荐阅读
- git - 编辑特定提交并重新应用后续提交
- flutter - 用飞镖颤振 FCM
- twilio - 在 Studio Flow 中,如何知道 Gather-Input-On-Call 小部件是否以无输入或超时结束
- excel - 如何解决 VBA 中日期的类型不匹配(运行错误 13)?
- java - 在 Java 与 Postman 中连接到 https 服务器
- python - 如何从 YieldWatch 中获取“净值”?
- entity-framework - 如何防止实体框架在数据库优先方法中将空字符串转换为 null
- python - 在 Flask 上注销时更改用户的布尔值
- c# - 从脚本返回值
- javascript - AWS Lambda /tmp 文件夹不在执行之间共享