Delete Data from Cache with SQL and Named Tags
NCache provides Object Queries in order to delete the particular item from the cache having the Named Tag and its value as provided.
Pre-Requisites
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime
- The application must be connected to cache before performing the operation.
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Note
Use fully-qualified name of the class Product e.g. Data.Product
.
An example below shows how to delete items associated with a Named Tag using object queries. Make sure that item is added in the cache with the Named Tags. Refer to the Add Items with Named Tags section to get a detail on creating and adding Named Tags.
try
{
// Pre-condition: Cache is already connected
// Create SQL Query with the specified criteria
// Make sure to use the fully qualified class name
string query = "DELETE Data.Product WHERE this.FlashSaleDiscount = ?";
// Create a new hashtable
Hashtable values = new Hashtable();
// Add the name(s) and value(s) of Named Tags in the hashtable for
// query searching values
values.Add("FlashSaleDiscount", 0.5);
// ExecuteNonQuery processes the query and returns the number of affected rows
int rowsAffected = cache.ExecuteNonQuery(query, queryValue);
// 'rowsAffected' number of items were removed from cache
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
In order to get more detail on object queries please refer to the SQL Reference for NCache section.
Another approach that can be used in order to delete Named Tags using object queries; is to fetch the data by querying it. Use the Remove method on the fetched data to remove the selected values. Using this approach the items associated with a specific Named Tag are removed. However, it is not a recommended approach as it will increase the network calls which is not very efficient for the user.
In order to get more detail on object queries please refer to the SQL Reference for NCache section.
See Also
SQL Query with Named Tags
Remove Named Tags
Add/Update Data in Cache with Named Tags
Using Tags