如何在sql依赖项asp.net中检测哪个表已更改

时间:2020-01-22 19:02:34

标签: asp.net asp.net-mvc sqldependency

我的数据库中有两个表。使用sqlcommand中的分号将这两个表连接在一起。我已经使用SQL依赖项来通知有关更改。但是我想知道的是,在sqlDep_OnChange中我如何知道哪个表已被修改为第一个或第二个。

 public void ProductNotification()
    {
        string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
        var  sqlCommand = new[] { @"SELECT [ID] from  [dbo].[Products]", @"SELECT [ID] from [dbo].[Customers]"};

        using (SqlConnection con = new SqlConnection(conStr))
        {
            SqlCommand cmd = new SqlCommand(string.Join("; ", sqlCommand), con);

            if (con.State != System.Data.ConnectionState.Open)
            {
                con.Open();
            }
            cmd.Notification = null;
            SqlDependency sqlDep = new SqlDependency(cmd);
            sqlDep.OnChange += sqlDep_OnChange;
            //we must have to execute the command here
            using (SqlDataReader reader = cmd.ExecuteReader())
            {

        }
    }
}


void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{

    //which tables has been inserted is the first or second
    if (e.Info == SqlNotificationInfo.Insert)
    {

        SqlDependency sqlDep = sender as SqlDependency;
        sqlDep.OnChange -= sqlDep_OnChange;


        var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        notificationHub.Clients.All.notify("added");
        //re-register notification
        ProductNotification();
    }
}

0 个答案:

没有答案