【发布时间】:2020-01-20 18:13:06
【问题描述】:
我有以下代码,它使用 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>
【问题讨论】:
标签: asp.net asp.net-mvc sqldependency