NCache 4.4 - Online Documentation

Grouping Cached Data

 
Adding an Item to Data Group
 
Data can be added to NCache asynchronously using AddAsync method.
 
In this example an object is added to the cache asynchronously. The following code adds an item to cache with data group "Product" and sub group "Beverages". In this example, AddOperation will be used to set group and sub-group of the item.
 
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
string key = "Product:" + product.ProductID;
try
{
    cache.Add(key, product, "Product", "Beverages");
}
catch (OperationFailedException ex )
{
    // handle exception
}
 
Adding Data Group with CacheItem
 
In this example data group is set by assigning it as a property of CacheItem.
 
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
string key = "Product:" + product.ProductID;
CacheItem cacheItem=new CacheItem(product);
cacheItem.Group="Product";
cacheItem.SubGroup="Beverages";
try
{
    cache.Add(key, cacheItem);
}
catch (Exception ex )
{
    // handle exception
}
 
Updating an Item in a Data Group
 
If the user adds an item without any group or wants to add a group with that cached item, then he/she has to to first remove that item from the cache then insert/Add that item within the desired group and sub group. Otherwise, insert operation throws data groups mismatch exception.
 
Retrieving Keys Pertaining to a Particular Group
 
To return the list of keys that belong to a specified group and sub-group, the GetGroupKey method can be used. This method returns an arrayList of keys.
 
try
{
    ArrayList keys = cache.GetGroupKeys("Product", "Beverages");
 
    foreach (object obj in keys)
    {
        // do something
    }
}
catch (Exception ex )
{
    // handle exception
}
 
Retrieving Keys and Values Pertaining to a Particular Group
 
To return the dictionary of keys and values that belong to a specified group and sub-group, the GetGroupData method can be used. This method returns a dictionary of keys and values.
 
try
{
    IDictionary dict = cache.GetGroupData("Product","Beverages") as System.Collections.IDictionary;
 
    if (dict.Count> 0)
    {
        IDictionaryEnumerator ide = dict.GetEnumerator();
        while (ide.MoveNext())
        {
            string key = (string)ide.Key;
            object val = (object)ide.Value;
            // do something
        }
    }
}
catch (Exception ex )
{
    // handle exception
}
 
Removing a Data Group
 
The following code removes all items from data sub group 'Beverages' inside group 'Product'.
 
try
{
    cache.RemoveGroupData("Product", "Beverages");
}
catch (Exception ex )
{
    // handle exception
}
 
 
See Also