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
Did you find this article useful?
If you think your friends will like it too, share it on Facebook.
You have only to press the button here below!