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

範例

以下程式碼範例使用 and 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 及 2005 SQL Server)中,SqlCacheDependency 類別監控特定的 SQL Server 資料庫資料表。 當表格變更時,與表格相關的項目會從 中移除 Cache,並將該項目的新版本加入 Cache

SqlCacheDependency 類別也支援與 System.Data.SqlClient.SqlDependency 類別的整合,當使用 SQL Server 2005 資料庫時。 2005 SQL Server 的查詢通知機制偵測資料變更導致 SQL 查詢結果失效,並從 System.Web.Caching.Cache 移除與該 SQL 查詢相關的快取項目。

你可以使用 SqlCacheDependency 類別,在使用 SQL Server 2005 時,將依賴於 SQL Server 資料庫資料表或 SQL 查詢的項目加入應用程式的 Cache。 你也可以搭配 @ OutputCache 指令使用此類別,使輸出快取頁面或使用者控制項依賴於SQL Server資料庫資料表。 最後,你可以使用 SqlCacheDependency 類別搭配 @ OutputCache 頁面指令,讓輸出快取頁面依賴於 SQL 查詢結果,使用SQL Server 2005 版本。 使用 SQL Server 2005 的查詢通知不被 @ OutputCache 指令用於使用者控制。

Note

為了讓這個類別在使用基於資料表的通知時正常運作,資料庫以及你想要依賴的資料表必須啟用通知功能。 你可以透過呼叫類別的方法 SqlCacheDependencyAdmin 或使用 aspnet_regsql.exe 命令列工具來啟用通知。 此外,應用程式的 Web.config 檔案中必須包含適當的設定設定。

使用 SqlCacheDependency 物件並SQL Server 2005 查詢通知,並不需要任何明確設定。 請參閱SQL Server文件,了解使用查詢通知時允許的 Transact-SQL 查詢類型限制資訊。

以下範例展示了一個 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>

建構函式

名稱 Description
SqlCacheDependency(SqlCommand)

初始化該類別的新實例 SqlCacheDependency ,利用提供的 SqlCommand 資料建立快取金鑰相依關係。

SqlCacheDependency(String, String)

初始化該類別的新實例 SqlCacheDependency ,利用所提供的參數建立快取金鑰相依關係。

屬性

名稱 Description
HasChanged

會得到一個值,表示物件是否 CacheDependency 改變。

(繼承來源 CacheDependency)
UtcLastModified

會顯示依賴性最後變更的時間。

(繼承來源 CacheDependency)

方法

名稱 Description
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>)

新增一個動作方法,用來通知相關方對此相依變更的通知。

(繼承來源 CacheDependency)
SetUtcLastModified(DateTime)

標記依賴性最後一次變更的時間點。

(繼承來源 CacheDependency)
TakeOwnership()

允許第一個使用者宣告對此依賴的專屬擁有權。

(繼承來源 CacheDependency)
ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

適用於

另請參閱