Benvenuti da Idea R | Vicenza - Romano di Lombardia (Bergamo)

Blog

Prendere uno smanettone del software degli anni 80, aggiungere un graphic designer di nuova generazione e allungare il tutto con uno studioso di strategie di marketing. Agitare energicamente e si ottiene il blog Idea R.

How to clear the SqlDataSource cache

Pubblicato il 12/24/2011
Categorie: Applicazioni Web

Questo articolo è disponibile anche in italiano.

The SqlDataSource.EnableCaching property allows to save the results of a specific database query.
When the caching is activated, if you reset EnableCaching to false, the query result is not retrieved from the cache anymore but it's re-executed every time.
But surprisingly, if you reset EnableCaching to true again, the data is retrieved from the old cache.

// The Customers table contains PIPPO as the name of the customer 1
SqlDataSource dataSource = new SqlDataSource(myConnectionString, "SELECT Name FROM Customers WHERE CustomerID = 1");
dataSource.EnableCaching = true;
// The query returns PIPPO
...
// Update the database changing the name of the customer 1 to MINNY
...
dataSource.EnableCaching = false;
// This time the cache is disabled, so the query returns MINNY
...
dataSource.EnableCaching = true;
// WARNING! The query returns the old and expired value PIPPO again


To clear the cache then it is useless to set EnableCaching to true, but we must proceed using the SqlDataSource.CacheDependency properties.

// The Customers table contains PIPPO as the name of the customer 1
SqlDataSource dataSource = new SqlDataSource(myConnectionString, "SELECT Name FROM Customers WHERE CustomerID = 1");
dataSource.EnableCaching = true;
dataSource.CacheKeyDependency = "MyCacheKey";
if (Cache["MyCacheKey"] == null] Cache["MyCacheKey"] = DateTime.Now;
// The query returns PIPPO
 
...
 
// Update the database changing the name of the customer 1 to MINNY
 
...
 
Cache["MyCacheKey"] = DateTime.Now; // Clear the cache
// Now the query correctly returns MINNY
newsletter

Did you like the article?

Subscribe to our free newsletter and stay up to date on digital strategies.

Sei il lettore numero 20,993.

Commenti

Articolo precedente

Articolo precedente

Menu dropdown con CSS

Articolo successivo

Riflessi sull'acqua con Photoshop

Articolo successivo