1

我对 SqlCacheDependency 有一个问题,我无法解决这个问题。CacheItemRemovedCallback 将在我使用通知查询时向缓存中添加某些内容时立即触发(当我使用 databaseEntryName 和 tableName 时它可以工作,但这对我来说是生硬的)。我已经检查了http://msdn.microsoft.com/en-us/library/ms181122.aspx大约 20 次,但我仍然找不到我做错了什么。

我正在使用的代码:

string connString = MsSqlUtil.GetConnectionString();
System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connString);
System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connString, "Product");
SqlDependency.Start(connString);

Product product = ProductProvider.Get(10);

using (SqlConnection connection = new SqlConnection(connString))
{

  SqlCommand cmdProduct = new SqlCommand(@"
  SET ANSI_NULLS ON
  SET ANSI_PADDING ON
  SET ANSI_WARNINGS ON
  SET CONCAT_NULL_YIELDS_NULL ON
  SET QUOTED_IDENTIFIER ON
  SET NUMERIC_ROUNDABORT OFF
  SET ARITHABORT ON
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED 
  SELECT dbo.Product.ProductId, dbo.Product.Name FROM dbo.Product WHERE dbo.Product.ProductId = 10", connection);

  SqlCacheDependency myProductDependency = new SqlCacheDependency(cmdProduct);

  if (connection.State == ConnectionState.Closed)
  {
    connection.Open();
  }

  using (SqlDataReader reader = cmdProduct.ExecuteReader())
  {
    while (reader.Read())
    {
    }
  }

  HttpContext.Current.Cache.Add("Product:10", product, myProductDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, OnRemove);

}


//Callback
public static void OnRemove(string key, object cacheItem, System.Web.Caching.CacheItemRemovedReason reason)
{
//this fires directly and the reason is always DependencyChanged however nothing has changed in the database, weird!
}

我知道查询一定有问题,因为http://msdn.microsoft.com/en-us/library/ms181122.aspx告诉我“如果这些选项或隔离级别设置不正确,则会触发通知SELECT 语句执行后立即执行。” 但是我不知道出了什么问题。ProductId 列的类型为 int,名称为 nvarchar(50)

4

1 回答 1

1

观看QN: SQL Profiler 中的订阅事件类。运行你的测试用例。将触发一个带有EventSubClass值 Subscription 的事件。将TextData完全包含订阅通知InfoSourceType(我认为它将在EventTextXML 元素中)。

有了这个,您将确切地知道您的查询是如何不符合要求的,并且您可以相应地解决问题。

于 2014-08-14T10:33:53.383 回答