asp.net-mvc-4signalrsqldependencyquery-notifications

Is it possible to make count Query for SQl Dependency?


Concerning SignalR and SQL Dependency, is it true that the Query Notification can't use aggregate function like count(*)?

Do one have another way or an idea for create query that contain aggregate function ?


Solution

  • Yes, this is the solution if you want to use an aggregate function like COUNT(*) with SqlDependency.

    First, in your repository, you will still use a SELECT query. But in the reader, you just count the rows of data when the reader executes the command. Something like this:

    int count = 0;
    
    command = new SqlCommand(
        @"select Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN.ID_BUKTI_PEMBAYARAN " +
        @"from Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN " +
        @"where Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN.IS_NEW = @room",
        connect);
    command.Parameters.AddWithValue("room", true);
    
    try
    {
        command.Notification = null;
        
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        
        if (connect.State == ConnectionState.Open)
            connect.Close();
            
        connect.Open();
        
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            count++;
        }
        
        return count;
    }
    catch { return 0;}
    finally { connect.Close(); }