How to call a c# function when an SQL Server table changes

Asked

Viewed 221 times

0

I have the following code on C# Asp.NET 4.5 to count the number of records in my table

[HttpGet]
[Route("consult")]
public HttpResponseMessage GetAll()
{
    try
    {
        MatrizGeneral matriz = null;
        //int count = 0;

        using (SqlConnection connection = new SqlConnection(this.ConnectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandText = "select count(*) from AVL_Ignition";

                SqlDataReader reader = command.ExecuteReader();
                matriz.size= (Int32)command.ExecuteScalar();

            }
            connection.Close();
        }
         return Request.CreateResponse(HttpStatusCode.OK, matriz);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

I would like this function to be executed every time there is a change in my table (whenever there is a insert, update, etc), searching the Internet, I found something with SqlDependency but I didn’t quite understand.

How could I apply the SqlDependency in my code?

  • 2

    At what point? Why can you call this method (which has problems) at the time you do the operations, but apparently you want it to be automatic? but, at what point in what situations, explain better?

  • Hello @Virgilionovic, sorry for the lack of explanation. The table mentioned in the question is being changed by a Teltonika device (vehicle management equipment in construction), which is communicating with the bank and filling this table. This equipment can do various Inserts or updates for 1 day, (I have no control over it ) and because I don’t know when the last or how many changes were made to the table, I was thinking of a way to do it automatically. (WHENEVER there is a change in the table run my function).

  • I hope to have clarified everything that was not well detailed in the question.

  • If the command is made by an equipment, it can call pages itself? because this is a web application? how will you control who calls? understood!

  • Another thing who will need this value, who will want this value ... hope you understand that I did not understand where, when and how this value will be used.

1 answer

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.