Add Data to Cache
After successful initialization of the cache and gaining a valid cache handle,
you can perform an Add
operation. Add is a basic operation provided by
NCache, and this can be used to add/update data to the cache using multiple API
calls.
Key-Value cache store
NCache uses a “key” and “value” structure for objects. Every object must have a
unique string key associated with it. Every key has an atomic occurrence in the
cache whether it is local or clustered. Cached keys are case sensitive in
nature, and if you try to add another key with same value, an
OperationFailedException
is thrown by the cache.
Custom Objects
The value of the objects stored in the cache can range from being simple string
types to complex objects. However, the custom object data must be serializable
otherwise NCache will throw a serialization exception. You can also add data
using the setValue
method of the CacheItem
class, which results in the data
being saved internally as a CacheItem
.
Additionally, you can use the NCache Dynamic Compact Serialization framework for custom objects. This framework provides cost effective serialization facilities for registered classes.
Note
NCache returns CacheItemVersion with every Add/Insert call. In the following
examples, the use of CacheItemVersion
has been ignored.
To utilize the APIs, include the following namespace in your application: Alachisoft.NCache.Web.Caching.
Adding Objects to Cache
In order to add data in cache it must be ensured that the object is either .NET serialized or registered with NCache Compact Serialization Framework. In this example, a new object of Product class is created and added to cache.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
product.UnitsInStock = 15;
string key = "Product:" + product.ProductID;
try
{
cache.Add(key, product);
}
catch (OperationFailedException ex)
{
// handle exception
// usually thrown if key already exists in cache
// however verify the failure reason
}
Adding Objects Using CacheItem
CacheItem
is a custom class provided by NCache which can be used to add data
to the cache. This class encapsulates data as its value property. CacheItem
also
lets you set additional specifications associated with an object as properties
of this class.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
product.UnitsInStock = 15;
CacheItem cacheItem = new CacheItem(product);
string key = "Product:" + product.ProductID;
try{
cache.Add(key, cacheItem);
}
catch (OperationFailedException ex){
// handle exception
}