SqlCacheDependency Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Stabilisce una relazione tra un elemento archiviato in un oggetto dell'applicazione Cache ASP.NET e una tabella di database di SQL Server specifica o 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à
Esempio
Nell'esempio di codice seguente vengono utilizzati 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 SqlCacheDependency , la pagina aggiunge un elemento a Cache con una dipendenza dall'oggetto SqlCacheDependency . È consigliabile usare la gestione delle eccezioni simile a quella illustrata di seguito.
<%@ 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 classe SqlCacheDependency monitora una tabella di database SQL Server specifica. Quando la tabella viene modificata, gli elementi associati alla tabella vengono rimossi da Cachee viene aggiunta una nuova versione dell'elemento all'oggetto Cache.
La classe SqlCacheDependency supporta anche l'integrazione con la classe System.Data.SqlClient.SqlDependency quando si usa un database SQL Server 2005. Il meccanismo di notifica delle query di SQL Server 2005 rileva le modifiche ai dati che invalidano i risultati di una query SQL e rimuove tutti gli elementi memorizzati nella cache associati alla query SQL dalla System.Web.Caching.Cache.
È possibile usare la classe SqlCacheDependency per aggiungere elementi all'Cache dell'applicazione 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 direttiva @ OutputCache per rendere una pagina memorizzata nella cache di output o un controllo utente dipendente da una tabella di database SQL Server. Infine, è possibile usare la classe SqlCacheDependency con la direttiva della pagina @ OutputCache per rendere una pagina memorizzata nella cache di output dipendente dai risultati di una query SQL quando si usa SQL Server 2005. La notifica delle query che usa SQL Server 2005 non è supportata nella direttiva @ OutputCache per i controlli utente.
Note
Affinché questa classe funzioni correttamente quando si usano notifiche basate su tabelle, il database e le tabelle in cui si desidera creare dipendenze devono avere notifiche abilitate. È possibile abilitare le notifiche chiamando metodi della SqlCacheDependencyAdmin classe o usando lo aspnet_regsql.exe strumento da riga di comando. Inoltre, le impostazioni di configurazione appropriate devono essere incluse nel file di Web.config dell'applicazione.
L'uso di un oggetto SqlCacheDependency con notifica di query SQL Server 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 delle 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
| Nome | Descrizione |
|---|---|
| SqlCacheDependency(SqlCommand) |
Inizializza una nuova istanza della SqlCacheDependency classe utilizzando l'oggetto fornito SqlCommand per creare una dipendenza della chiave della cache. |
| SqlCacheDependency(String, String) |
Inizializza una nuova istanza della SqlCacheDependency classe utilizzando i parametri forniti per creare una dipendenza della chiave della cache. |
Proprietà
| Nome | Descrizione |
|---|---|
| HasChanged |
Ottiene un valore che indica se l'oggetto CacheDependency è stato modificato. (Ereditato da CacheDependency) |
| UtcLastModified |
Ottiene l'ora dell'ultima modifica della dipendenza. (Ereditato da CacheDependency) |
Metodi
| Nome | Descrizione |
|---|---|
| CreateOutputCacheDependency(String) |
Crea una relazione di dipendenza tra un elemento archiviato in un oggetto ASP.NET'applicazione OutputCache e una tabella di database SQL Server. |
| DependencyDispose() |
Rilascia le risorse usate dalla CacheDependency classe e dalle classi che derivano da CacheDependency. (Ereditato da CacheDependency) |
| Dispose() |
Rilascia le risorse utilizzate 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 il Type dell'istanza corrente. (Ereditato da Object) |
| GetUniqueID() |
Recupera un identificatore univoco per un SqlCacheDependency oggetto . |
| 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 del Objectcorrente. (Ereditato da Object) |
| NotifyDependencyChanged(Object, EventArgs) |
Notifica all'oggetto di base CacheDependency che la dipendenza rappresentata da una classe derivata è stata modificata CacheDependency . (Ereditato da CacheDependency) |
| SetCacheDependencyChanged(Action<Object,EventArgs>) |
Aggiunge un metodo Action per gestire la notifica alle parti interessate nelle modifiche apportate a questa dipendenza. (Ereditato da CacheDependency) |
| SetUtcLastModified(DateTime) |
Contrassegna l'ora dell'ultima modifica di 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) |