LINQ with NCache

NOTE: This feature is not available in NCache Express and Professional edition.

LINQ is a set of new programming semantics that allows you to unify the way of accessing data of any kind. Data can be found in collection of domain objects, XML document, object graph, tree structure, Linked list etc. LINQ unify the way of accessing data in all sources of information you can deal with, while writing your code.

So basically, LINQ helps you in:

Unifying the way of accessing data from different data sources (Objects, database, XML etc).

It shields you from learning the specification details of each data source.

We integrate LINQ with NCache by implementing a class named "NCacheQuery", which further implements the interface called "IQueryable" provided by .NET framework. This integration allows you to run LINQ queries on your cached items. For executing LINQ queries on your cached items you are supposed to define an object implementing IQueryable interface and pass an instance of cache which contains the object as shown below:

IQueryable<Product> products = new NCacheQuery<Product>(_cache);

NCache is integrated with LINQ in such a way that no code change is required except that you will have to add a new assembly reference and namespace in your application rest of the code will work without any change. NCache only support single entity search, multiple entities or joins are not supported.

Include the following namespace in your application for LINQ support:

usingAlachisoft.NCache.Linq;

The following code shows how to implement the NCacheQuery class which further implements IQueryable interface. The code also shows the LINQ query based on NCache Query Language running on a cached data.

namespaceNCacheLINQ

{

classProgram

{

staticvoid Main (string[] args)

{

IQueryable<Product> products = new NCacheQuery<Product>(_cache);

try

{

var result1 = from product in products

where product.ProductID > 10

select product;

if (result1 != null)

{

foreach (Product p in result1)

{

Console.WriteLine("ProductID : " + p.ProductID);

}

}

else

{

Console.WriteLine("No record found.");

}

}

catch (Exception)

{

Console.WriteLine(_error);

}

Console.WriteLine("Press Enter to continue..");

Console.ReadLine();

}

}

}

There are some LINQ operators which are not supported by NCache queries, those are:

NCache queries does not support nested queries.

LINQ operator ORDERBY is not supported by NCache queries as SQL Server has an in-built orderby operator.

LINQ operator GROUPBY is not supported by NCache queries as SQL Server has an in-built groupby operator.

Join operations are not supported by NCache queries.

User has to go through the trouble of indexing the data first, through NCache Manager.