当SQL DB表中有更改时,我正在使用SQL依赖关系来更新dashoboard。 我在app_start()事件中从Global.asax文件调用以下方法。
public void InitialiseMetricsDependency()
{
try
{
using (var connection = new SqlConnection(_connString))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var command = new SqlCommand("SELECT [id],[Application],[customerName],[Actual] FROM [dbo].[Metrics]", connection))
{
command.Notification = null;
dependency = new SqlDependency(command);
dependency.OnChange += dependency_OnChange;
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
}
}
}
catch (Exception ex)
{
Log.Error(ex.InnerException.StackTrace);
}
}
现在我有以下dependency_OnChange事件
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
try
{
if (e.Type == SqlNotificationType.Change)
{
using (var connection = new SqlConnection(_connString))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var command = new SqlCommand("SELECT [id],[Application],[customerName],[Actual] FROM [dbo].[Metrics]", connection))
{
command.Notification = null;
dependency = new SqlDependency(command);
dependency.OnChange += dependency_OnChange;
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
}
}
//push data to client
}
}
catch (Exception ex)
{
Log.Error(ex.InnerException.StackTrace);
}
}
我正在通过其他API更新Metrics表,因此Api运行并更新Metircs表中的每一行。因此,on_change事件的每一行都会触发。 如果API值与现有行值相同,仍然依赖于dependency_OnChange事件
如果值真的发生变化,我怎样才能触发dependency_OnChange事件?