Using DELETE Statement
Similar to SQL, NCache lets you delete the data from the cache based on the given criteria. The delete statement is executed through ExecuteNonQuery()
which returns the number of the deleted rows as a result of the query executed.
Note
The Delete
statement can only be executed through ExecuteNonQuery
:
Pre-Requisites
- Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
- 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.
The following example deletes all the products from the cache with the UnitsInStock equals to 0 and returns the number of rows deleted using ExecuteNonQuery.
try
{
// Pre-condition: Cache is already connected
// Items are already present in the cache
// Specify the query with the specified criteria
// Use the fully qualified name of your own custom class
string query = "DELETE Alachisoft.NCache.Sample.Data.Product WHERE this.UnitsInStock = ?";
// Add the values in the hashtable for executing query
Hashtable values = new Hashtable();
values.Add("UnitsInStock", 0);
// Deletes all the items from the cache with unitsInStock greater than 0
int result = cache.ExecuteNonQuery(query, values);
// Return number of affected rows.
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("Incorrect query format"))
{
// Make sure that the query format is correct
}
else if (ex.Message.Contains("Index is not defined"))
{
// Make sure that index is defined using Query Indexes through NCache Manager
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Additional Resources
NCache provides sample application for SQL Searching at:
Shipped with NCache: %NCHOME%\samples\dotnet\ObjectQueryLanguage
See Also
Using Locks for Concurrent Updates
SQL Search for Objects
SQL Search for Keys
Using IN Operator
Using Like Operator
Query Operators
Search Cache with LINQ