I'm using SqlDependency to control my cache. I want to use it to monitor several tables (around 10). There should be one SqlDependency per watched table.
Should I create for each of them code like that:
public void CreateDependency_Table()
{
if (connectionStringSettings != null)
{
using (SqlConnection conn = new SqlConnection(connectionStringSettings.ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT id from dbo.Table", conn))
{
cmd.Notification = null;
SqlDependency sqlDependency = new SqlDependency(cmd);
sqlDependency.OnChange += new OnChangeEventHandler(sqlDep_Table_OnChange);
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
}
}
}
}
}
and:
private void sqlDep_Table_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= sqlDep_Table_OnChange;
MyCacheWhatever.Clear();
//Re-attach dependency
CreateDependency_Table();
}
or can I reuse something between them? Like connection?
Is this the preferred way of setting multiple notifications?
Here I'll show you a linq extension that may help you:
I've designed the below class that hook up a listener for one or more queries, it may not be the best solution but it works.
So it will create an object for every trigger that can, for example, be used to trigger the SinalR. You just need to start the Dependency and the class SqlDependencyHelper within the Global.asax and everything will be stored within the SqlDataManagement like if the trigger is an update or delete and which id has changed.
A third field within the SELECT that is called ReferenceItem can be used to know if the trigger happened due to an update, so I used the DateTime DB column called lastChanged to know which row has updated.
All queries must be from a list and using the format below
Select Sample
@"SELECT 'PreStartPhotos' as QueryReferenceName, [id], '' as ReferenceItem FROM [dbo].[PreStartPhotos]"
Classes
}