Cache Handle from EF Core Context
NCache's EF Core Extension Methods also allow for flexibility when dealing with entities directly through the cache. These APIs do not involve the data source, so data is being directly entered and removed from the cache without modifying the data source. Such APIs are handy for data that is not to be changed frequently.
Note
This feature is also available in NCache Professional.
To utilize NCache EF Core APIs, include the following namespaces in your application:
NCache provides the following APIs for caching purposes:
EF Core Context: Get Cache Instance
The cache handle is obtained via the GetCache, NCache EF Core extension method on your application’s extended DbContext
class.
public partial class NorthwindContext : DbContext
{
// Class configures cache with NCacheConfiguration.Configure() method
}
Cache-only API calls are made via the Cache
wrapper returned when the GetCache method is called. The cache wrapper is associated with the context in use. Entities and their respective requests are verified for their types before the necessary operations are invoked. This verification takes place with the help of the context at hand that is initialized when the GetCache call is made. Hence, to successfully execute requests, the context must be alive (not disposed) when the requests are made. Failing to do so will throw System.ObjectDisposedException
.
Thus, in code, it is advised to carry out cache-only operations within the context:
Important
If the cache is not initialized, it throws an exception and all the operations that need to be further performed will fail till cache initialization.
using (var context = new NorthwindContext())
{
Cache cache = context.GetCache(); // get NCache instance
// Perform cache-only operations
}
Insert
The Insert method adds the entity directly to the cache without any dependency on the database. You might be storing a new customer in the database and have already fetched all previously added customers into your cache. Instead of executing a LINQ query later to fetch the new customer from the data source into the cache, you can simply call Insert right after the customer is added into the database (when SaveChanges
is called) with the same instance of the entity
used for insertion into the database. This saves the cost of a database trip for one entity.
Entities can be cached with the following CachingOptions:
QueryIdentifier
Priority
AbsoluteExpirationTime
SlidingExpirationTime
Important
- The value for
StoreAs
isSeparateEntities
, as entities insert into the cache as separate entities through this API. - Database dependency cannot be injected through this API because there are no queries made over the cache through Insert. Therefore, the CreateDbDependency property in CachingOptions is ignored within this call.
The
Insert returns a cache key which is generated internally for every entity being stored in the cache. This cache key can be saved to be used later for verification purposes or to remove the cache entity.
The Remove method removes entities from the cache, without deleting them from the database. This is useful if you have made some temporary changes to the cached entities or the entities might be stale. Removing the entities from the cache allows loading fresh data from a data source, either through the This API has two overloads, one which takes an entity, while the other takes in the cache key corresponding to the entity. This key is returned during the
The RemoveByQueryIdentifier method removes all entities from the cache based on the specified NCache provides a sample application for EF Core on GitHub. .NET: Alachisoft.NCache.EntityFrameworkCore and Alachisoft.NCache.Runtime.Caching namespaces.Insert
method behaves as follows:
Case
Behavior
Entity not existing in the cache
Adds entity into the cache
Entity existing in the cache
Updates entity in the cache
Examples
Default
priority.using (var database = new NorthwindContext())
{
var cust = new Customers
{
CustomerId = "HANIH",
ContactName = "Hanih Moos",
ContactTitle = "Sales Representative",
CompanyName = "Blauer See Delikatessen"
};
var options = new CachingOptions
{
QueryIdentifier = new Tag("CustomerEntity"),
Priority = Runtime.CacheItemPriority.Default
};
Cache cache = database.GetCache(); // get NCache instance
cache.Insert(cust, out string cacheKey, options);
string key = cacheKey; // can be saved for future use such as removing cache
}
using (var database = new NorthwindContext())
{
// Customer entity to be cached and stored to database
var customerEntity = new Customers
{
CustomerId = "HANIH",
ContactName = "Hanih Moos",
ContactTitle = "Sales Representative ",
CompanyName = "Blauer See Delikatessen"
};
// Add customer entity to database
database.Customers.Add(customerEntity);
database.SaveChanges();
// Caching options for cache
var options = new CachingOptions
{
QueryIdentifier = new Tag("CustomerEntity"),
Priority = Runtime.CacheItemPriority.Default,
};
// Add customer entity to cache
Cache cache = database.GetCache();
cache.Insert(cust, out string cacheKey, options);
string key = cacheKey; // can be saved for future use such as removing cache
}
Remove
FromCache
or LoadIntoCache
methods.Insert/FromCache/LoadIntoCache
calls when the entity is added to the cache and can be saved.public void Remove(object entity);
public void Remove(string cacheKey);
Examples
using (var database = new NorthwindContext())
{
var cust = new Customers
{
CustomerId = "HANIH",
ContactName = "Hanih Moos",
ContactTitle = "Sales Representative",
CompanyName = "Blauer See Delikatessen"
};
ICache cache = database.GetCache();
cache.Remove(cust);
}
using (var database = new NorthwindContext())
{
Cache cache = database.GetCache();
cache.Remove(cacheKey); // cacheKey saved during Insert()/FromCache()/LoadIntoCache() calls
}
RemoveByQueryIdentifier
QueryIdentifier
in CachingOptions (when inserting into the cache). If entities with the identifier exist, all associated entities are removed from the cache but not from the actual data source.using (var database = new NorthwindContext())
{
var options = new CachingOptions
{
QueryIdentifier = new Tag("CustomerEntity"),
};
Cache cache = database.GetCache(); // get NCache instance
cache.RemoveByQueryIdentifier(options.QueryIdentifier);
}
Sample Code
See Also