使用SqlCacheDependency类,从而在底层数据改变时使缓存中的数据到期。SqlCacheDependency建立了缓存与数据库的一个关系,如果数据库的数据发生了改变,有这样依赖的缓存中的项将从缓存中释放,原先建立这个缓存项的代码可以在此从数据库获取值。
为了说明这一点,下面使用CreateSqlCacheDependency方法为Microsoft SQL Server中pubs数据库的Authors表创建一个SqlCacheDependency对象,pubs数据库是一个随SQL Server2000发行的事例数据库:
public
SqlCacheDependency CreateSqlCacheDependency(
string
connStr)
{
// Make a dependency on the authors database table so that
// if it changes, the cached data will also be disposed of.

// Make sure we are enabled for notifications for the db.
// Note that the parameter has to be the actual connection
// string NOT the connection string NAME from web.config.
SqlCacheDependencyAdmin.EnableNotifications(connStr);

// Make sure we are enabled for notifications for the table.
SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "Authors");

// This is case-sensitive so make sure the first entry
// matches the entry in the web.config file exactly.
// The first parameter here must be the connection string
// NAME not the connection string itself…
return new SqlCacheDependency("pubs", "Authors");
}
SqlCacheDependencyAdmin类负责与SQL Server通信,建立必要的基础设施。以便 qlCacheDependency
正确的触发。在应用web.config文件中configuration/system.web/caching下有一部分定义了SqlC acheDependency 依赖性基于哪些参数操作。对于轮询时间(仅适用于SQL Server 2000,因为SQL Server 2005不会轮询)和连接时间有一些超时设置,另外还有一个指向连接串的链接,从而可以连接串名来使用连接串,这个 连接可以在web.config中配置,如下所示
<
caching
>
<
sqlCacheDependency
enabled
="True"
pollTime
="60000"
>
<
databases
>
<
add
name
="pubs"
connectionStringName
="LocalPubs"
pollTime
="9000000"
/>
</
databases
>
</
sqlCacheDependency
>
</
caching
>

<
connectionStrings
>
<
add
name
="LocalPubs"
connectionString
="Server=(local);Integrated
Security=True;Database=pubs;Persist Security Info=True"
providerName
="System.Data.SqlClient"
/>
</
connectionStrings
>
使用SqlCacheDependency类时,首先要确保已经对数据库和所监视的表启用了通知(代码中紫色字体),如果对数据库或者数据库表未启用通知,构造 SqlCacheDependency时就会抛出( DatabaseNotEnabledForNotificationException )异常。
为了说明这一点,下面使用CreateSqlCacheDependency方法为Microsoft SQL Server中pubs数据库的Authors表创建一个SqlCacheDependency对象,pubs数据库是一个随SQL Server2000发行的事例数据库:




















SqlCacheDependencyAdmin类负责与SQL Server通信,建立必要的基础设施。以便 qlCacheDependency
正确的触发。在应用web.config文件中configuration/system.web/caching下有一部分定义了SqlC acheDependency 依赖性基于哪些参数操作。对于轮询时间(仅适用于SQL Server 2000,因为SQL Server 2005不会轮询)和连接时间有一些超时设置,另外还有一个指向连接串的链接,从而可以连接串名来使用连接串,这个 连接可以在web.config中配置,如下所示














使用SqlCacheDependency类时,首先要确保已经对数据库和所监视的表启用了通知(代码中紫色字体),如果对数据库或者数据库表未启用通知,构造 SqlCacheDependency时就会抛出( DatabaseNotEnabledForNotificationException )异常。