Bagikan melalui


SqlCacheDependency Kelas

Definisi

Membuat hubungan antara item yang disimpan dalam objek aplikasi Cache ASP.NET dan tabel database SQL Server tertentu atau hasil kueri SQL Server 2005. Kelas ini tidak dapat diwariskan.

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
Warisan
SqlCacheDependency

Contoh

Contoh kode berikut menggunakan SqlDataSource kontrol dan GridView untuk menampilkan tabel database. Saat halaman dimuat, halaman mencoba membuat SqlCacheDependency objek. SqlCacheDependency Setelah objek dibuat, halaman menambahkan item ke Cache dengan dependensi pada SqlCacheDependency objek. Anda harus menggunakan penanganan pengecualian yang mirip dengan yang ditunjukkan di sini.

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

Keterangan

Pada semua versi SQL Server yang didukung (Microsoft SQL Server 7.0, Microsoft SQL Server 2000, dan SQL Server 2005) SqlCacheDependency kelas memantau tabel database SQL Server tertentu. Saat tabel berubah, item yang terkait dengan tabel dihapus dari Cache, dan versi baru item ditambahkan ke Cache.

Kelas ini SqlCacheDependency juga mendukung integrasi dengan System.Data.SqlClient.SqlDependency kelas saat menggunakan database SQL Server 2005. Mekanisme pemberitahuan kueri SQL Server 2005 mendeteksi perubahan pada data yang membatalkan hasil kueri SQL dan menghapus item cache apa pun yang terkait dengan kueri SQL dari System.Web.Caching.Cache.

Anda dapat menggunakan SqlCacheDependency kelas untuk menambahkan item ke aplikasi Cache Anda yang bergantung pada tabel database SQL Server atau pada kueri SQL saat menggunakan SQL Server 2005. Anda juga dapat menggunakan kelas ini dengan direktif @ OutputCache untuk membuat halaman yang di-cache output atau kontrol pengguna bergantung pada tabel database SQL Server. Terakhir, Anda dapat menggunakan SqlCacheDependency kelas dengan @ OutputCache direktif halaman untuk membuat halaman yang di-cache output bergantung pada hasil kueri SQL saat menggunakan SQL Server 2005. Pemberitahuan kueri menggunakan SQL Server 2005 tidak didukung pada direktif @ OutputCache untuk kontrol pengguna.

Catatan

Agar kelas ini berfungsi dengan benar saat menggunakan pemberitahuan berbasis tabel, database dan tabel apa pun yang ingin Anda buat dependensinya harus mengaktifkan pemberitahuan. Anda dapat mengaktifkan pemberitahuan dengan memanggil metode SqlCacheDependencyAdmin kelas atau dengan menggunakan aspnet_regsql.exe alat baris perintah. Selain itu, pengaturan konfigurasi yang tepat harus disertakan dalam file Web.config aplikasi.

SqlCacheDependency Menggunakan objek dengan pemberitahuan kueri SQL Server 2005 tidak memerlukan konfigurasi eksplisit apa pun. Lihat dokumentasi SQL Server untuk informasi tentang pembatasan jenis kueri Transact-SQL yang diizinkan saat menggunakan pemberitahuan kueri.

Contoh berikut menunjukkan file ASP.NET Web.config yang memungkinkan dependensi berbasis tabel pada tabel database 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>

Konstruktor

SqlCacheDependency(SqlCommand)

Menginisialisasi instans SqlCacheDependency baru kelas , menggunakan yang disediakan SqlCommand untuk membuat dependensi kunci cache.

SqlCacheDependency(String, String)

Menginisialisasi instans SqlCacheDependency baru kelas , menggunakan parameter yang disediakan untuk membuat dependensi cache-key.

Properti

HasChanged

Mendapatkan nilai yang menunjukkan apakah CacheDependency objek telah berubah.

(Diperoleh dari CacheDependency)
UtcLastModified

Mendapatkan waktu ketika dependensi terakhir diubah.

(Diperoleh dari CacheDependency)

Metode

CreateOutputCacheDependency(String)

Membuat hubungan dependensi antara item yang disimpan dalam objek aplikasi OutputCache ASP.NET dan tabel database SQL Server.

DependencyDispose()

Merilis sumber daya yang digunakan oleh CacheDependency kelas dan kelas apa pun yang berasal dari CacheDependency.

(Diperoleh dari CacheDependency)
Dispose()

Merilis sumber daya yang digunakan oleh CacheDependency objek .

(Diperoleh dari CacheDependency)
Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
FinishInit()

Menyelesaikan inisialisasi CacheDependency objek.

(Diperoleh dari CacheDependency)
GetFileDependencies()

Mendapatkan dependensi file.

(Diperoleh dari CacheDependency)
GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetType()

Mendapatkan dari instans Type saat ini.

(Diperoleh dari Object)
GetUniqueID()

Mengambil pengidentifikasi unik untuk SqlCacheDependency objek.

ItemRemoved()

Dipanggil ketika entri cache yang dipantau dihapus.

(Diperoleh dari CacheDependency)
KeepDependenciesAlive()

Memperbarui waktu akses terakhir setiap item cache yang bergantung pada item ini.

(Diperoleh dari CacheDependency)
MemberwiseClone()

Membuat salinan dangkal dari saat ini Object.

(Diperoleh dari Object)
NotifyDependencyChanged(Object, EventArgs)

Memberi tahu objek dasar CacheDependency bahwa dependensi yang diwakili oleh kelas turunan CacheDependency telah berubah.

(Diperoleh dari CacheDependency)
SetCacheDependencyChanged(Action<Object,EventArgs>)

Menambahkan metode Tindakan untuk menangani pemberitahuan pihak yang tertarik dalam perubahan pada dependensi ini.

(Diperoleh dari CacheDependency)
SetUtcLastModified(DateTime)

Menandai waktu saat dependensi terakhir diubah.

(Diperoleh dari CacheDependency)
TakeOwnership()

Memungkinkan pengguna pertama untuk mendeklarasikan kepemilikan eksklusif atas dependensi ini.

(Diperoleh dari CacheDependency)
ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)

Berlaku untuk

Lihat juga