首页 > 解决方案 > 如何使用 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>

标签: asp.netasp.net-mvcsqldependency

解决方案


您可以通过查看 eventArgs.Info属性轻松找出更改类型。


推荐阅读