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建立物件之後,頁面會將專案新增至 Cache ,且相依于 SqlCacheDependency 物件。 您應該使用類似此處所示的例外狀況處理。

<%@ 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

類別 SqlCacheDependency 也支援在使用 SQL Server 2005 資料庫時與 System.Data.SqlClient.SqlDependency 類別整合。 SQL Server 2005 的查詢通知機制會偵測資料變更,使 SQL 查詢的結果失效,並從 中移除與 SQL 查詢 System.Web.Caching.Cache 相關聯的任何快取專案。

您可以使用 類別, SqlCacheDependency 在使用 SQL Server 2005 時,將專案新增至 Cache 相依于SQL Server資料庫資料表或 SQL 查詢的應用程式。 您也可以使用這個類別搭配 @ OutputCache 指示詞,讓輸出快取頁面或使用者控制項相依于SQL Server資料庫資料表。 最後,您可以使用 類別 SqlCacheDependency 搭配 @ OutputCache page 指示詞,在使用 SQL Server 2005 時,讓輸出快取頁面相依于 SQL 查詢的結果。 使用者控制項的 指示詞不支援使用 SQL Server 2005 的 @ OutputCache 查詢通知。

注意

若要讓這個類別在使用資料表型通知時正確運作,資料庫和您想要建立相依性的任何資料表都必須啟用通知。 您可以呼叫 類別的方法 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)

適用於

另請參閱