SqlCacheDependency 类

定义

在存储于 ASP.NET 应用程序的 Cache 对象中的项与特定 SQL Server 数据库表或 SQL Server 2005 的查询结果之间建立关系。 此类不能被继承。

public ref class SqlCacheDependency sealed : System::Web::Caching::CacheDependency
public sealed class SqlCacheDependency : System.Web.Caching.CacheDependency
type SqlCacheDependency = class
    inherit CacheDependency
Public NotInheritable Class SqlCacheDependency
Inherits CacheDependency
继承
SqlCacheDependency

示例

下面的代码示例使用 SqlDataSourceGridView 控件显示数据库表。 加载页面时,页面会尝试创建 SqlCacheDependency 对象。 SqlCacheDependency创建 对象后,页面会将一个依赖于 对象的SqlCacheDependency项添加到 Cache 中。 应使用类似于此处所示的异常处理。

<%@ Page Language="C#" Debug="true" %>
<%@ import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
// <snippet2>
    public void Page_Load(object Src, EventArgs E) 
    { 
        // Declare the SqlCacheDependency instance, SqlDep. 
        SqlCacheDependency SqlDep = null; 
        
        // Check the Cache for the SqlSource key. 
        // If it isn't there, create it with a dependency 
        // on a SQL Server table using the SqlCacheDependency class. 
        if (Cache["SqlSource"] == null) { 
            
            // Because of possible exceptions thrown when this 
            // code runs, use Try...Catch...Finally syntax. 
            try { 
                // Instantiate SqlDep using the SqlCacheDependency constructor. 
                SqlDep = new SqlCacheDependency("Northwind", "Categories"); 
            } 
            
            // Handle the DatabaseNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableNotifications method. 
            catch (DatabaseNotEnabledForNotificationException exDBDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableNotifications("Northwind"); 
                } 
                
                // If the database does not have permissions set for creating tables, 
                // the UnauthorizedAccessException is thrown. Handle it by redirecting 
                // to an error page. 
                catch (UnauthorizedAccessException exPerm) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 
            
            // Handle the TableNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method. 
            catch (TableNotEnabledForNotificationException exTabDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableTableForNotifications("Northwind", "Categories"); 
                } 
                
                // If a SqlException is thrown, redirect to an error page. 
                catch (SqlException exc) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 
            
            // If all the other code is successful, add MySource to the Cache 
            // with a dependency on SqlDep. If the Categories table changes, 
            // MySource will be removed from the Cache. Then generate a message 
            // that the data is newly created and added to the cache. 
            finally { 
                Cache.Insert("SqlSource", Source1, SqlDep); 
                CacheMsg.Text = "The data object was created explicitly."; 
                
            } 
        } 
        
        else { 
            CacheMsg.Text = "The data was retrieved from the Cache."; 
        } 
    } 
// </snippet2>
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <p>
        </p>
        <p>
            <asp:SqlDataSource id="Source1" runat="server" SelectCommand="SELECT * FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName]=@CategoryName,[Description]=@Description,[Picture]=@Picture WHERE [CategoryID]=@CategoryID" ConnectionString="<%$ ConnectionStrings:Northwind %>"></asp:SqlDataSource>
            <asp:GridView id="GridView1" runat="server" DataKeyNames="CategoryID" AllowSorting="True" AllowPaging="True" DataSourceID="Source1"></asp:GridView>
        </p>
        <p>
        </p>
        <p>
            <asp:Label id="CacheMsg" runat="server" AssociatedControlID="GridView1"></asp:Label>
        </p>
   </form>
</body>
</html>
<%@ Page Language="VB" Debug="True" %>
<%@ import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' <snippet2>
    Sub Page_Load(Src As Object, E As EventArgs)
       ' Declare the SqlCacheDependency instance, SqlDep.
       Dim SqlDep As SqlCacheDependency

       ' Check the Cache for the SqlSource key.
       ' If it isn't there, create it with a dependency
       ' on a SQL Server table using the SqlCacheDependency class.
       If Cache("SqlSource") Is Nothing

          ' Because of possible exceptions thrown when this
          ' code runs, use Try...Catch...Finally syntax.
          Try
             ' Instantiate SqlDep using the SqlCacheDependency constructor.
             SqlDep = New SqlCacheDependency("Northwind", "Categories")

          ' Handle the DatabaseNotEnabledForNotificationException with
          ' a call to the SqlCacheDependencyAdmin.EnableNotifications method.
          Catch exDBDis As DatabaseNotEnabledForNotificationException
             Try
                SqlCacheDependencyAdmin.EnableNotifications("Northwind")

             ' If the database does not have permissions set for creating tables,
             ' the UnauthorizedAccessException is thrown. Handle it by redirecting
             ' to an error page.
             Catch exPerm As UnauthorizedAccessException
                 Response.Redirect(".\ErrorPage.htm")
             End Try

          ' Handle the TableNotEnabledForNotificationException with
                ' a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method.
          Catch exTabDis As TableNotEnabledForNotificationException
             Try
                SqlCacheDependencyAdmin.EnableTableForNotifications( _
                 "Northwind", "Categories")

             ' If a SqlException is thrown, redirect to an error page.
             Catch exc As SqlException
                 Response.Redirect(".\ErrorPage.htm")
             End Try

          ' If all the other code is successful, add MySource to the Cache
          ' with a dependency on SqlDep. If the Categories table changes,
          ' MySource will be removed from the Cache. Then generate a message
                ' that the data is newly created and added to the cache.
          Finally
             Cache.Insert("SqlSource", Source1, SqlDep)
                CacheMsg.Text = "The data object was created explicitly."

          End Try

        Else
           CacheMsg.Text = "The data was retrieved from the Cache."
        End If
    End Sub
' </snippet2>

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <p>
        </p>
        <p>
            <asp:SqlDataSource id="Source1" runat="server" SelectCommand="SELECT * FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName]=@CategoryName,[Description]=@Description,[Picture]=@Picture WHERE [CategoryID]=@CategoryID" ConnectionString="<%$ ConnectionStrings:Northwind %>"></asp:SqlDataSource>
            <asp:GridView id="GridView1" runat="server" DataKeyNames="CategoryID" AllowSorting="True" AllowPaging="True" DataSourceID="Source1"></asp:GridView>
        </p>
        <p>
        </p>
        <p>
            <asp:Label id="CacheMsg" runat="server" AssociatedControlID="GridView1"></asp:Label>
        </p>
   </form>
</body>
</html>

注解

在所有受支持的 SQL Server (Microsoft SQL Server 7.0、Microsoft SQL Server 2000 和 SQL Server 2005) SqlCacheDependency 类监视特定的 SQL Server 数据库表。 当表更改时,与表关联的项将从 Cache中删除,并将该项的新版本添加到 。Cache

使用 SQL Server 2005 数据库时, System.Data.SqlClient.SqlDependencySqlCacheDependency还支持与 类集成。 SQL Server 2005 的查询通知机制检测使 SQL 查询结果失效的数据更改,并从 中删除与 SQL 查询 System.Web.Caching.Cache关联的任何缓存项。

使用 SQL Server 2005 时, SqlCacheDependency 可以使用 类将依赖于 SQL Server 数据库表或 SQL 查询的项添加到应用程序的 Cache 。 还可以将此类与 指令结合使用 @ OutputCache ,使输出缓存页或用户控件依赖于 SQL Server 数据库表。 最后,可以在使用 SQL Server 2005 时,将 SqlCacheDependency 类与 page 指令结合使用 @ OutputCache ,使输出缓存页依赖于 SQL 查询的结果。 用户控件的 指令不支持 @ OutputCache 使用 SQL Server 2005 的查询通知。

注意

为了使此类在使用基于表的通知时正常工作,数据库和要依赖的任何表都必须启用通知。 可以通过调用 类的方法 SqlCacheDependencyAdmin 或使用 aspnet_regsql.exe 命令行工具来启用通知。 此外,应用程序的 Web.config 文件中必须包含正确的配置设置。

SqlCacheDependency将 对象与 SQL Server 2005 查询通知结合使用不需要任何显式配置。 有关在使用查询通知时允许的 Transact-SQL 查询类型的限制的信息,请参阅 SQL Server 文档。

以下示例演示一个 ASP.NET Web.config 文件,该文件在 SQL Server 数据库表上启用基于表的依赖项。

<configuration>
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=(local); Initial Catalog=northwind; Integrated Security=true"; providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <caching>
      <sqlCacheDependency enabled = "true" pollTime = "60000" >
        <databases>
          <add name="northwind"
            connectionStringName="Northwind"
            pollTime="9000000"
            />
        </databases>
      </sqlCacheDependency>
    </caching>
  </system.web>
</configuration>

构造函数

SqlCacheDependency(SqlCommand)

初始化 SqlCacheDependency 类的新实例,并使用提供的 SqlCommand 创建缓存键依赖项。

SqlCacheDependency(String, String)

初始化 SqlCacheDependency 类的新实例,并使用提供的参数创建缓存键依赖项。

属性

HasChanged

获取一个值,该值指示 CacheDependency 对象是否已更改。

(继承自 CacheDependency)
UtcLastModified

获取依赖项的上次更改时间。

(继承自 CacheDependency)

方法

CreateOutputCacheDependency(String)

创建 ASP.NET 应用程序的 OutputCache 对象中存储的项与 SQL Server 数据库表之间的依赖关系。

DependencyDispose()

释放由 CacheDependency 类和从 CacheDependency 派生的所有类使用的资源。

(继承自 CacheDependency)
Dispose()

释放由 CacheDependency 对象使用的资源。

(继承自 CacheDependency)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
FinishInit()

完成 CacheDependency 对象的初始化。

(继承自 CacheDependency)
GetFileDependencies()

获取文件依赖项。

(继承自 CacheDependency)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
GetUniqueID()

检索 SqlCacheDependency 对象的唯一标识符。

ItemRemoved()

删除监视的缓存项时调用。

(继承自 CacheDependency)
KeepDependenciesAlive()

更新依赖于此项的每个缓存项的上次访问时间。

(继承自 CacheDependency)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
NotifyDependencyChanged(Object, EventArgs)

通知 CacheDependency 基对象由派生的 CacheDependency 类表示的依赖项已更改。

(继承自 CacheDependency)
SetCacheDependencyChanged(Action<Object,EventArgs>)

添加 Action 方法,处理通知感兴趣的参与方有关此依赖项的更改。

(继承自 CacheDependency)
SetUtcLastModified(DateTime)

标记依赖项的上次更改时间。

(继承自 CacheDependency)
TakeOwnership()

允许第一个用户声明对此依赖项的独占拥有权。

(继承自 CacheDependency)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅