Getting data from SqlDependency

后端 未结 7 619
别那么骄傲
别那么骄傲 2021-01-02 06:25

I\'ve got a table and a SqlDependency that is waiting for new inserts.

OnChange fires as I need, but I don\'t understand if it\'s possible to get the row which caus

7条回答
  •  独厮守ぢ
    2021-01-02 06:50

    I hope this helps you:

         string commandString = string.Format("SELECT [Id] FROM [dbo].[Tech]");
         command = new SqlCommand(commandString, connection);
    
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            SqlDependency dependency = (SqlDependency)sender;
            dependency.OnChange -= dependency_OnChange;
    
            this.Dispatcher.Invoke((System.Action)(() =>
            {
    
                if (e.Info.ToString().ToLower().Trim() == "insert")
                {
                    GetData();
                    int NewTechID = TechIDs.Last();
                }
    
            }));
        }
    
        private void GetData()
        {
            command.Notification = null;
            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
    
            command.Connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    TechIDs.add(int.Parse(reader.GetValue(0).ToString()));
                }
                reader.Close();
            }
            command.Connection.Close();
        }
    

提交回复
热议问题