关于sql缓存依赖如何工作

时间:2014-08-26 18:50:50

标签: c# sql-server caching sqlcachedependency

这里我通过这个网站 http://www.dotnetcurry.com/showarticle.aspx?ID=263 查看有关sql缓存依赖的文章。特别是调用了一个例程,它首次缓存表数据,当基础表数据被更改时,例程将再次从表中加载数据。我只是不明白数据库中的数据更改何时自动缓存将如何为空或无效。所以我在这里粘贴那个例程,我只是不明白db中数据发生变化时缓存数据是如何失效的?

只需查看例程并讨论这一点:在db中发生数据更改时缓存数据如何失效

public static class MyExtensions
{
    public static List<T> LinqCache<T>(this Table<T> query) where T : class
    {
        string tableName = query.Context.Mapping.GetTable(typeof(T)).TableName;
        List<T> result = HttpContext.Current.Cache[tableName] as List<T>;

        if (result == null)
        {
            using (SqlConnection cn = new SqlConnection(query.Context.Connection.ConnectionString))
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand(query.Context.GetCommand(query).CommandText, cn);
                cmd.Notification = null;
                cmd.NotificationAutoEnlist = true;
                                        SqlCacheDependencyAdmin.EnableNotifications(query.Context.Connection.ConnectionString);
                if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(query.Context.Connection.ConnectionString).Contains(tableName))
                {
                        SqlCacheDependencyAdmin.EnableTableForNotifications(query.Context.Connection.ConnectionString, tableName);
                }                   

                SqlCacheDependency dependency = new SqlCacheDependency(cmd);
                cmd.ExecuteNonQuery();

                result = query.ToList();
                HttpContext.Current.Cache.Insert(tableName, result, dependency);
            }
        }
        return result;
    }
}

who will create this table AspNet_SqlCacheTablesForChangeNotification ? what is the importance of this table AspNet_SqlCacheTablesForChangeNotification ? 假设我的员工表中的数据发生了变化,那么这个表AspNet_SqlCacheTablesForChangeNotification

会发生什么

请讨论我的所有观点,因此我的所有怀疑都将清楚sql依赖如何工作以及如何自动缓存无效?

感谢

1 个答案:

答案 0 :(得分:2)

自SQL Server 2005以来,数据库实现了通知机制,以通知应用程序有关更改的信息 - http://en.wikipedia.org/wiki/SQL_Server_Notification_Services

在此之前,他们只是定期轮询数据库中的变化。

此处提供更多信息 - http://www.asp.net/web-forms/tutorials/data-access/caching-data/using-sql-cache-dependencies-cs