Good day! How can I update a DataTable using SqlDependency ?

 public void StartWatching() { SqlDependency.Stop(connectionString); SqlDependency.Start(connectionString); ExecuteWatchingQuery(); } static void Main(string[] args) {} private void ExecuteWatchingQuery() { using(SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using(var command = new SqlCommand( "select * from Shedule", connection)) { var sqlDependency = new SqlDependency(command); bool res = SqlDependency.Start(connectionString); sqlDependency.OnChange += new OnChangeEventHandler(OnDatabaseChange); command.ExecuteReader(); } } Console.Read(); } private void OnDatabaseChange(object sender, SqlNotificationEventArgs args) { SqlNotificationInfo info = args.Info; if (SqlNotificationInfo.Insert.Equals(info) || SqlNotificationInfo.Update.Equals(info) || SqlNotificationInfo.Delete.Equals(info)) Console.WriteLine("Change..."); ExecuteWatchingQuery(); } 

That's about. The program is written in the Console app.

  • In the OnDatabaseChange event OnDatabaseChange open the connection to the database, and read the new data in the DataTable . - Alexander Petrov
  • static void Main(string[] args) {} what does this method do? The class methods of the console application itself, if you plan to call them in Main should be static. This is only a quick look. Or in the given code a hodgepodge of methods of different classes? - rdorn

1 answer 1

See it.

Conventional CRUD operations do not give you the opportunity to find out if the database has been updated from some other application, unless it is reread from time to time.

SqlDependency allows you to find out when a certain part of the database will change, but does not provide you with new data. Therefore, you should do this:

  1. Create a SqlDependency and subscribe to OnChange .
  2. Load data in the usual way, without SqlDependency .
  3. Upon the arrival of OnChange you know that the data has changed, so you need to re-read the data just like in step 2.