是否可以对 SQl 依赖项进行计数查询?

Is it possible to make count Query for SQl Dependency?

关于SignalR和SQL依赖,Query Notification是否真的不能使用count(*)这样的聚合函数?

是否有其他方法或想法来创建包含聚合函数的查询?

是的,如果您想使用像 count(*) 这样的聚合函数来查询 sql 依赖项,我有解决方案。首先在您的存储库中仍然使用 select query 。但是在 reader 中你只计算 reader 执行命令的数据。像这样

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(); }

小心使用SqlDependency class - it has the problems with memory leaks. Hovewer, you can use an open source realization of the SqlDependency class - SqlDependencyEx。它使用数据库触发器和本机 Service Broker 通知来接收有关 table 更改的事件。这是一个用法示例:

int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
          TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) 
{
    sqlDependency.TableChanged += (o, e) => changesReceived++;
    sqlDependency.Start();

    // Make table changes.
    MakeTableInsertDeleteChanges(changesCount);

    // Wait a little bit to receive all changes.
    Thread.Sleep(1000);
}

Assert.AreEqual(changesCount, changesReceived);

使用 SqlDependecyEx,您可以仅监视 INSERT 或 DELETE,避免 UPDATE,这会为您提供理想的结果:类似 COUNT 的行为。希望这有帮助。