Unable to invalidate the cache dependent on sql query
I am trying to invalidate the cache based on the change in the rows of the database. I have achieved su开发者_如何学编程ccess while doing the same thing with linq with the same database and table but Iam not able to do it in the basic way:
Here is the code that I have written, please help:
public DataSet GetData(string sqlCmd)
{
string connectionStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string cacheKey = "test123";
DataSet ds = (DataSet)HttpRuntime.Cache.Get(cacheKey);
if (ds != null)
{
return ds;
}
SqlCacheDependency sqldep = null;
SqlConnection conn = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlCmd, conn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlDataAdapter sqlAd = new SqlDataAdapter(cmd);
ds = new DataSet();
sqlAd.Fill(ds);
System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connectionStr);
string NotificationTable = "TblMetaData";
if (!System.Web.Caching.SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connectionStr).Contains(NotificationTable))
System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connectionStr, NotificationTable);
sqldep = new SqlCacheDependency(cmd);
HttpRuntime.Cache.Insert(cacheKey, ds, sqldep);
return ds;
}
I am using Sql Server 2005 and using the fully qualified queries that can work with command notification.
My other code in Linq is perfectly working with the same database and table, so there is no point about the Service Broker or other permissions not set. PLease help me to get rid of this problem.
This article has some troubleshooting steps The Mysterious Notification, along with an explanation how things work that helps where trying to understand why something is broken. Your should validate that each piece of the machinery works:
- check the a subscription notification gets created in
sys.dm_qn_subscriptions
- check that a notification gets fired
- check that the notification gets delivered (you can safely ignore everything about routing and remote delivery in this link, though, since SqlDependency is always local)
On an unrelated note, you can use LINQ-to-SQL and Query Notifications directly: LinqToCache.
The best thing to do is: Take a look on the sql log, if any problem with Notifications is happening, log will show!
the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n
In my case, The problem occurred because of database restoration, to solve, log showed me the problem, then, I execute
use DatabaseName EXEC sp_changedbowner 'sa'
精彩评论