Use LINQ Query for Objects
Note
This feature is only available in NCache Enterprise Edition.
To utilize the benefits of LINQ, it is integrated with NCache using the NCacheQuery class, which implements the IQueryable interface provided by the .NET framework. This integration allows the user to query objects using LINQ.
No code change is required for using NCache with LINQ aside from cache initialization and the previously mentioned interface implementation along with the expected new assembly reference and namespace additions. The rest of the code will work without any change in application.
Querying Objects through NCacheQuery class
You can use any of the following supported LINQ operators to retrieve NCache objects using NCacheQuery:
- Projection Operators
- Restriction Operators
- Basic Query Operators
- Logical Operators
- Aggregation Operators
- Wildcard Query Operators
The code belows demonstrates all the following operators in the way they are intended to be used.
Prerequisites
- To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
- Indexing for searchable objects and their attributes need to be configured first as explained on our section on Dynamic Indexing and Configuring Query Indexes and in the Administrator's Guide.
- For API details, refer to: NCacheQuery.
LINQ Operations
The following code uses the NCacheQuery class uses several of the operators we've discussed to demonstrate how to use NCache with LINQ.
Using Query Expression
try
{
// Precondition: Cache is already connected
// Create custom class LINQ object
IQueryable<Product> products = new NCacheQuery<Product>(cache);
// LINQ query to search cache
IQueryable<Product> result = from prod in products where (prod.Category == "Beverages" || prod.Category == "Dairy") && prod.UnitsInStock > 10 select prod;
if (result != null)
{
foreach (Product product in result)
{
Console.WriteLine($"Product '{product.ProductName}' in Category '{product.Category}' has stock of '{product.UnitsInStock}' units");
}
}
else
{
Console.WriteLine($"No product found");
}
}
catch (OperationFailedException ex)
{
//NCache specific exception
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Using Lambda Expression
// Lambda expression for same query
IQueryable<Product> result = products.Select(prod => prod).Where(prod => ((prod.Category == "Beverages" || prod.Category == "Dairy") && prod.UnitsInStock > 10));
Additional Resources
NCache provides sample application for NCache LINQ on GitHub.
See Also
LINQ Reference for NCache
Configure LINQPad for NCache
Event Notifications in Cache