user1372051
user1372051

Reputation: 21

C# How to monitoring the change of table of the database

How do I monitor changes to my database tables in C#? I'm using SQL Server 2008, and I want to synchronize data when a table has been changed.

Upvotes: 0

Views: 4103

Answers (2)

Likurg
Likurg

Reputation: 2760

If I understand you correctly, you want to create a SqlDependency;

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
  // Assume connection is an open SqlConnection.

  // Create a new SqlCommand object.
  SqlCommand command=new SqlCommand(
    "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
    connection);

  // Create a dependency and associate it with the SqlCommand.
  SqlDependency dependency=new SqlDependency(command);
  // Maintain the refence in a class member.

  // Subscribe to the SqlDependency event.
  dependency.OnChange+=new OnChangeEventHandler(OnDependencyChange);

  // Execute the command.
  command.ExecuteReader();
  // Process the DataReader.
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationsEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency
    SqlDependency.Stop(connectionString, queueName);
}

Upvotes: 3

Siddharood
Siddharood

Reputation: 988

Check Microsoft Sync Framework.

Upvotes: 2

Related Questions