SqlCacheDependency Classe

Definizione

Stabilisce una relazione tra un elemento archiviato in un oggetto Cache di un'applicazione ASP.NET e una tabella di database di SQL Server specifica oppure i risultati di una query di SQL Server 2005. La classe non può essere ereditata.

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
Ereditarietà
SqlCacheDependency

Esempio

Nell'esempio di codice seguente vengono usati i SqlDataSource controlli e GridView per visualizzare una tabella di database. Quando la pagina viene caricata, la pagina tenta di creare un SqlCacheDependency oggetto. Dopo aver creato l'oggetto, la SqlCacheDependency pagina aggiunge un elemento all'oggetto Cache con una dipendenza dall'oggetto SqlCacheDependency . È consigliabile usare la gestione delle eccezioni simile a quella illustrata qui.

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

Commenti

In tutte le versioni supportate di SQL Server (Microsoft SQL Server 7.0, Microsoft SQL Server 2000 e SQL Server 2005) la SqlCacheDependency classe monitora una tabella di database SQL Server specifica. Quando la tabella cambia, gli elementi associati alla tabella vengono rimossi dall'oggetto Cachee viene aggiunta una nuova versione dell'elemento all'oggetto Cache.

La SqlCacheDependency classe supporta anche l'integrazione con la System.Data.SqlClient.SqlDependency classe quando si usa un database SQL Server 2005. Il meccanismo di notifica della query di SQL Server 2005 rileva le modifiche ai dati che invalidano i risultati di una query SQL e rimuove eventuali elementi memorizzati nella cache associati alla query SQL dall'oggetto System.Web.Caching.Cache.

È possibile usare la SqlCacheDependency classe per aggiungere elementi all'applicazione Cache che dipendono da una tabella di database SQL Server o da una query SQL quando si usa SQL Server 2005. È anche possibile usare questa classe con la @ OutputCache direttiva per creare una pagina memorizzata nella cache di output o un controllo utente dipendente da una tabella di database SQL Server. Infine, è possibile usare la classe con la SqlCacheDependency@ OutputCache direttiva pagina per rendere una pagina memorizzata nella cache di output in base ai risultati di una query SQL quando si usa SQL Server 2005. La notifica di query con SQL Server 2005 non è supportata nella @ OutputCache direttiva per i controlli utente.

Nota

Per consentire a questa classe di funzionare correttamente quando si usano notifiche basate su tabelle, il database e le tabelle che si desidera creare dipendenze su devono avere notifiche abilitate. È possibile abilitare le notifiche chiamando metodi della SqlCacheDependencyAdmin classe o usando lo aspnet_regsql.exe strumento della riga di comando. Inoltre, le impostazioni di configurazione appropriate devono essere incluse nel file di Web.config dell'applicazione.

L'uso di un SqlCacheDependency oggetto con SQL Server notifica di query 2005 non richiede alcuna configurazione esplicita. Consultare la documentazione SQL Server per informazioni sulle restrizioni sui tipi di query Transact-SQL consentite quando si usa la notifica di query.

Nell'esempio seguente viene illustrato un file ASP.NET Web.config che abilita le dipendenze basate su tabelle in una tabella di 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>

Costruttori

SqlCacheDependency(SqlCommand)

Inizializza una nuova istanza della classe SqlCacheDependency utilizzando l'oggetto SqlCommand fornito per creare una dipendenza di chiave di cache.

SqlCacheDependency(String, String)

Inizializza una nuova istanza della classe SqlCacheDependency utilizzando i parametri forniti per creare una dipendenza di chiave di cache.

Proprietà

HasChanged

Ottiene un valore che indica se l'oggetto CacheDependency è stato modificato.

(Ereditato da CacheDependency)
UtcLastModified

Ottiene l'ora dell'ultima modifica apportata alla dipendenza.

(Ereditato da CacheDependency)

Metodi

CreateOutputCacheDependency(String)

Crea una relazione di dipendenza tra un elemento archiviato in un oggetto OutputCache di un'applicazione ASP.NET e una tabella di database di SQL Server.

DependencyDispose()

Rilascia le risorse utilizzate dalla classe CacheDependency e tutte le classi che derivano da CacheDependency.

(Ereditato da CacheDependency)
Dispose()

Rilascia le risorse usate dall'oggetto CacheDependency.

(Ereditato da CacheDependency)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
FinishInit()

Completa l'inizializzazione dell'oggetto CacheDependency.

(Ereditato da CacheDependency)
GetFileDependencies()

Ottiene le dipendenze del file.

(Ereditato da CacheDependency)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
GetUniqueID()

Recupera un identificatore univoco per un oggetto SqlCacheDependency.

ItemRemoved()

Chiamato quando viene rimossa una voce della cache monitorata.

(Ereditato da CacheDependency)
KeepDependenciesAlive()

Aggiorna l'ora dell'ultimo accesso di ogni elemento della cache che dipende da questo elemento.

(Ereditato da CacheDependency)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
NotifyDependencyChanged(Object, EventArgs)

Notifica all'oggetto CacheDependency di base che sono state apportate modifiche alla dipendenza rappresentata da una classe CacheDependency derivata.

(Ereditato da CacheDependency)
SetCacheDependencyChanged(Action<Object,EventArgs>)

Aggiunge un metodo azione per gestire l'invio delle notifiche alle parti interessate delle modifiche apportate a questa dipendenza.

(Ereditato da CacheDependency)
SetUtcLastModified(DateTime)

Indica l'ora dell'ultima modifica apportata a una dipendenza.

(Ereditato da CacheDependency)
TakeOwnership()

Consente al primo utente di dichiarare la proprietà esclusiva di questa dipendenza.

(Ereditato da CacheDependency)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche