SqlCacheDependency SqlCacheDependency SqlCacheDependency SqlCacheDependency Class

定義

在儲存於 ASP.NET 應用程式之 Cache 物件中的項目,和特定 SQL Server 資料庫資料表或 SQL Server 2005 查詢結果之間建立關聯性。Establishes a relationship between an item stored in an ASP.NET application's Cache object and either a specific SQL Server database table or the results of a SQL Server 2005 query. 這個類別無法被繼承。This class cannot be inherited.

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
繼承
SqlCacheDependencySqlCacheDependencySqlCacheDependencySqlCacheDependency

範例

下列程式碼範例會使用SqlDataSourceGridView控制項以顯示 資料庫資料表。The following code example uses the SqlDataSource and GridView controls to display a database table. 頁面載入頁面時,嘗試建立SqlCacheDependency物件。When the page is loaded, the page attempts to create a SqlCacheDependency object. 在後SqlCacheDependency建立物件、 頁面加入至項目Cache具有相依性SqlCacheDependency物件。After the SqlCacheDependency object is created, the page adds an item to the Cache with a dependency on the SqlCacheDependency object. 您應該使用例外狀況處理類似於如下所示。You should use exception handling similar to that shown here.

<%@ 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 資料庫資料表。On all supported versions of SQL Server (Microsoft SQL Server 7.0, Microsoft SQL Server 2000, and SQL Server 2005) the SqlCacheDependency class monitors a specific SQL Server database table. 當資料表變更,與資料表相關聯的項目會自Cache,並將新版本的項目加入CacheWhen the table changes, items associated with the table are removed from the Cache, and a new version of the item is added to the Cache.

SqlCacheDependency類別也支援與整合System.Data.SqlClient.SqlDependency類別時使用SQL Server 2005SQL Server 2005資料庫。The SqlCacheDependency class also supports integration with the System.Data.SqlClient.SqlDependency class when using a SQL Server 2005SQL Server 2005 database. 查詢通知機制SQL Server 2005SQL Server 2005偵測到使其失效的 SQL 查詢,並移除任何快取的項目相關聯的 SQL 查詢結果的資料變更System.Web.Caching.CacheThe query notification mechanism of SQL Server 2005SQL Server 2005 detects changes to data that invalidate the results of an SQL query and removes any cached items associated with the SQL query from the System.Web.Caching.Cache.

您可以使用SqlCacheDependency類別將項目新增至您的應用程式Cache使用時所依存的 SQL Server 資料庫資料表,或 SQL 查詢SQL Server 2005SQL Server 2005You can use the SqlCacheDependency class to add items to your application's Cache that are dependent on either a SQL Server database table or on an SQL query when using SQL Server 2005SQL Server 2005. 您也可以使用這個類別使用指示詞,使相依於 SQL Server 資料庫資料表的輸出快取的頁面或使用者控制項。You can also use this class with the directive to make an output-cached page or a user control dependent on a SQL Server database table. 最後,您可以使用SqlCacheDependencypage 指示詞,以讓輸出快取的頁面相依於 SQL 查詢的結果,當使用類別SQL Server 2005SQL Server 2005Finally, you can use the SqlCacheDependency class with the page directive to make an output-cached page dependent on the results of an SQL query when using SQL Server 2005SQL Server 2005. 查詢通知使用SQL Server 2005SQL Server 2005不支援使用者控制項的指示詞。Query notification using SQL Server 2005SQL Server 2005 is not supported on the directive for user controls.

注意

針對此類別才能正常運作時使用以資料表為基礎的通知,資料庫和任何您想要對相依性的資料表必須具有啟用通知。For this class to work correctly when using table-based notifications, the database and any tables that you want to make dependencies on must have notifications enabled. 您可以呼叫的方法,以啟用通知SqlCacheDependencyAdmin類別,或使用命令列工具。You can enable notifications by calling methods of the SqlCacheDependencyAdmin class or by using the command-line tool. 此外,應用程式的 Web.config 檔案中必須包含適當的組態設定。In addition, the proper configuration settings must be included in the application's Web.config file.

使用SqlCacheDependency物件SQL Server 2005SQL Server 2005查詢通知不需要任何明確的設定。Using a SqlCacheDependency object with SQL Server 2005SQL Server 2005 query notification does not require any explicit configuration. 請參閱SQL Server 2005SQL Server 2005線上叢書 》 的使用查詢通知時,不允許的 TRANSACT-SQL 查詢的類型限制的相關資訊。Consult the SQL Server 2005SQL Server 2005 Books Online for information about restrictions on the types of Transact-SQL queries that are allowed when using query notification.

下列範例顯示 ASP.NET Web.config 檔案,可讓資料表為基礎的 SQL Server 資料庫資料表的相依性。The following example shows an ASP.NET Web.config file that enables table-based dependencies on a SQL Server database table.

<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(SqlCommand) SqlCacheDependency(SqlCommand)

使用所提供的 SqlCacheDependency 建立快取索引鍵相依性,初始化 SqlCommand 類別的新執行個體。Initializes a new instance of the SqlCacheDependency class, using the supplied SqlCommand to create a cache-key dependency.

SqlCacheDependency(String, String) SqlCacheDependency(String, String) SqlCacheDependency(String, String) SqlCacheDependency(String, String)

使用所提供的參數建立快取索引鍵相依性,初始化 SqlCacheDependency 類別的新執行個體。Initializes a new instance of the SqlCacheDependency class, using the supplied parameters to create a cache-key dependency.

方法

CreateOutputCacheDependency(String) CreateOutputCacheDependency(String) CreateOutputCacheDependency(String) CreateOutputCacheDependency(String)

在存放於 ASP.NET 應用程式之 OutputCache 物件中的項目與 SQL Server 資料庫資料表之間建立相依性關係。Creates a dependency relationship between an item that is stored in an ASP.NET application's OutputCache object and a SQL Server database table.

DependencyDispose() DependencyDispose() DependencyDispose() DependencyDispose()

釋放由 CacheDependency 類別及任何衍生自 CacheDependency 的類別所使用的資源。Releases the resources used by the CacheDependency class and any classes that derive from CacheDependency.

(Inherited from CacheDependency)
Dispose() Dispose() Dispose() Dispose()

釋放 CacheDependency 物件所使用的資源。Releases the resources used by the CacheDependency object.

(Inherited from CacheDependency)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
FinishInit() FinishInit() FinishInit() FinishInit()

完成 CacheDependency 物件的初始化。Completes initialization of the CacheDependency object.

(Inherited from CacheDependency)
GetFileDependencies() GetFileDependencies() GetFileDependencies() GetFileDependencies()

取得檔案相依性。Gets the file dependencies.

(Inherited from CacheDependency)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
GetUniqueID() GetUniqueID() GetUniqueID() GetUniqueID()

擷取 SqlCacheDependency 物件的唯一識別項。Retrieves a unique identifier for a SqlCacheDependency object.

ItemRemoved() ItemRemoved() ItemRemoved() ItemRemoved()

已在移除受監視的快取項目時呼叫。Called when a monitored cache entry is removed.

(Inherited from CacheDependency)
KeepDependenciesAlive() KeepDependenciesAlive() KeepDependenciesAlive() KeepDependenciesAlive()

針對相依於這個項目的每個快取項目,更新上次存取時間。Updates the last access time of every cache item that depends on this item.

(Inherited from CacheDependency)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
NotifyDependencyChanged(Object, EventArgs) NotifyDependencyChanged(Object, EventArgs) NotifyDependencyChanged(Object, EventArgs) NotifyDependencyChanged(Object, EventArgs)

告知基底 CacheDependency 物件,由衍生的 CacheDependency 類別所表示的相依性已經變更。Notifies the base CacheDependency object that the dependency represented by a derived CacheDependency class has changed.

(Inherited from CacheDependency)
SetCacheDependencyChanged(Action<Object,EventArgs>) SetCacheDependencyChanged(Action<Object,EventArgs>) SetCacheDependencyChanged(Action<Object,EventArgs>) SetCacheDependencyChanged(Action<Object,EventArgs>)

加入 Action 方法來處理在變更此相依性時通知有興趣的對象。Adds an Action method to handle notifying interested party in changes to this dependency.

(Inherited from CacheDependency)
SetUtcLastModified(DateTime) SetUtcLastModified(DateTime) SetUtcLastModified(DateTime) SetUtcLastModified(DateTime)

標記上次變更相依性的時間。Marks the time when a dependency last changed.

(Inherited from CacheDependency)
TakeOwnership() TakeOwnership() TakeOwnership() TakeOwnership()

允許第一位使用者宣告這個相依性的獨佔擁有權。Allows the first user to declare exclusive ownership of this dependency.

(Inherited from CacheDependency)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

屬性

HasChanged HasChanged HasChanged HasChanged

取得值,指出 CacheDependency 是否已經變更。Gets a value indicating whether the CacheDependency object has changed.

(Inherited from CacheDependency)
UtcLastModified UtcLastModified UtcLastModified UtcLastModified

取得上次變更相依性的時間。Gets the time when the dependency was last changed.

(Inherited from CacheDependency)

適用於

另請參閱