Как узнать тип изменений, произошедших с базой данных, используя зависимость SQL - PullRequest
0 голосов
/ 20 января 2020

У меня есть следующий код, который мгновенно отображает данные о жизни с помощью SignalR. Таблица обновляется мгновенно с помощью сигнала, как только строка вставляется обновляется или удаляется. Тем не менее, я хотел бы знать, в частности, изменение типа, произошедшее с базой данных, будь то обновление удалить или вставить. Я понимаю, что метод 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>

1 Ответ

0 голосов
/ 20 января 2020

Вы можете легко узнать тип изменения, посмотрев на eventArgs.Info свойство .

...