• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Show / Hide Table of Contents
  • Programmer's Guide
  • Client Side API Programming
    • Setting Up Development Environment
    • Basic Cache Operations
      • Initialize Cache
      • Add Data to Cache
      • Update Data in Cache
      • Fetch Data From Cache
      • Remove Data From Cache
      • Dispose Cache
    • Bulk Operations
      • Adding Collection to Cache
      • Updating Collection in Cache
      • Retrieving Collection from Cache
      • Removing Collection from Cache
      • Deleting Collection from Cache
    • Asynchronous Operations
      • Using Asynchronous Operations
      • Using Asynchronous Operations with Callback Methods
    • Groups and Subgroups
      • Adding/Updating Data Group in Cache
      • Retrieving Data Group from Cache
      • Removing Data Group from Cache
    • Tagging Data in NCache
      • Creating Tags
      • Adding Items with Tags
      • Retrieving Previously Tagged Data
      • Removing Tagged Items from Cache
    • Named Tags
    • Data Expiration Strategies
      • Using Absolute Expiration
      • Using Sliding Expiration
    • Cache Dependencies
      • Key Dependency
      • File Dependency
      • Notification based Dependencies
        • Database Dependency using SQL Server
        • Database Dependency using Oracle
      • Polling Based Dependency
      • Custom Data Source Dependency
      • Multiple Cache Sync Dependency
      • Aggregate Dependency
      • Add Dependency to Existing Item
      • Using CLR Procedures to Call NCache
    • Locking Data in NCache
      • Locking Items in Cache (Pessimistic Locking)
      • Locking Items with Cache Item Versioning (Optimistic Locking)
    • SQL Reference for NCache
      • SQL Syntax
      • Querying Samples for Operators
      • Querying Data in NCache
      • NCache Language Integrated Query (LINQ)
        • Using LINQ in NCache
        • Configuring LINQPad for NCache
        • Querying NCache Data in LINQPad
    • Event Notifications
      • Cache Level Event Notifications
      • Item Level Event Notifications
      • Custom Event Notifications
    • Publish/Subscribe (Pub/Sub) in NCache
      • Pub/Sub Topics
      • Managing Topics
      • Pub/Sub Messages
        • Message Behavior and Properties
        • Creating a Message
      • Publish Messages to Topic
      • Subscribe for Topic Messages
      • Monitoring Pub/Sub Topics
    • Continuous Query
    • Using Streams in NCache
      • Opening with Stream Modes
      • Adding and Updating Data with Streams
      • Retrieving Data from Streams
      • Closing a Stream
    • Security and Encryption
      • NCache Security
      • NCache Data Encryption
    • Data Compression
    • NCache Management API
  • Server Side API Programming
    • Cache Startup Loader
      • Components of Cache Startup Loader
      • Sample Implementation of ICacheLoader on Single Node
      • Sample Implementation of ICacheLoader with Distribution Hints
    • Data Source Providers (Backing Source)
      • Read-Through Caching
        • Configure Read-Through Provider
        • Using Read-Through with Cache Operations
      • Write-Through Caching
        • Configuring Write-Through Provider
        • Using Write-Through with Basic Operations
        • Using Write-Behind with Basic Operations
        • Using Write-Behind with Bulk Operations
        • Using Write-Behind with Async Operations
        • Monitor Write-Through Counters
    • Custom Dependency
      • Sample Implementation of Custom Dependency
      • Sample Usage of Custom Dependency
    • WAN Replication through Bridge
      • Bridge Configurations
      • Implementing Bridge Conflict Resolver
    • Entry Processor
      • Sample Implementation of IEntryProcessor Interface
      • Sample Usage of EntryProcessor
    • MapReduce
      • Sample Implementation of MapReduce Interfaces
      • Sample Usage of MapReduce
    • Aggregator
      • Sample Implementation of IValueExtractor Interface
      • Sample Implementation of IAggregator Interface
      • Sample Usage of Aggregator
    • Dynamic Compact Serialization
  • Client Side ASP.NET Features
    • ASP.NET
      • ASP.NET Session State Provider for NCache
      • Multi-Region ASP.NET Session State Provider for NCache
    • ASP.NET Core
      • Session Storage in ASP.NET Core
        • Configure NCache ASP.NET Core Session Provider
        • Configure ASP.NET Core Sessions with NCache IDistributedCache Provider
      • Multi-Region ASP.NET Core Session Provider for NCache
      • Object Caching in ASP.NET Core
    • ASP.NET SignalR
      • Using NCache Extension for SignalR
    • View State Caching
      • Configuring and Using Content Optimization
      • Group View State with Sessions
      • Limit View State Caching
      • Perform Page Level Grouping for View State
    • ASP.NET Output Cache
      • Configure ASP.NET Output Caching
      • Using ASP.NET Output Cache with Custom Hooks
  • Client Side Third Party Integrations
    • Migrating AppFabric to NCache
      • AppFabric API vs. NCache API
    • NHibernate
      • NCache as NHibernate Second Level Cache
      • Using NHibernate Query Caching
      • Configuring Database Synchronization with NHibernate
    • Entity Framework Caching Integration
      • NCache as Entity Framework Second Level Cache
      • Entity Framework Caching Config File
    • Entity Framework Core Caching
      • Installing NCache Entity Framework Core Provider
      • Configuring NCache Entity Framework Core Provider
      • Using NCache Entity Framework Core Provider
        • Caching Options for EF Core Provider
        • LINQ APIs for EF Core Provider
        • Cache Only APIs for EF Core Provider
        • Query Deferred APIs for EF Core Provider
      • Logging in NCache Entity Framework Core Provider
    • Memcached
      • NCache Memcached Gateway Approach
      • Memcached Client Plugin for .NET
    • Debug NCache Providers in Visual Studio
    • NCache for Visual Studio Extension

Cache Only APIs for EF Core Caching Provider

NCache’s EF Core Caching Provider also allows flexibility to deal 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.

In order to utilize these APIs, include the following namespaces in your application:

  • Alachisoft.NCache.EntityFrameworkCore
  • Alachisoft.NCache.Runtime.Caching

NCache provides the following APIs for caching purposes:

  1. Insert
  2. Remove
  3. RemoveByQueryIdentifier

Get Cache Instance

The cache handle is obtained via the GetCache 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, in order to successfully execute requests, it is necessary that the context is 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:

using (NorthwindContext 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 into 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 is SeparateEntities as entities are inserted 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 method behaves as following:

Case Behavior
Entity not existing in cache Adds entity into the cache
Entity existing in cache Updates entity in the cache

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.

Examples

  • The following example inserts a Customer entity to the cache with Query identifier CustomerEntity and Default priority.
using (NorthwindContext database = new NorthwindContext())
{
    Customers cust = new Customers
    {
        CustomerId = "HANIH",
        ContactName = "Hanih Moos",
        ContactTitle = "Sales Representative",
        CompanyName = "Blauer See Delikatessen"
    };

    CachingOptions 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
}

  • This example caches the same entity being inserted into the database:
using (NorthwindContext database = new NorthwindContext())
{
    //Customer entity to be cached and stored to database
    Customers 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
    CachingOptions 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

The Remove method removes entities from 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 cache allows to load fresh data from data source, either through FromCache or LoadIntoCache methods.

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 Insert/FromCache/LoadIntoCache calls when the entity is added into the cache, and can be saved.

public void Remove(object entity);
public void Remove(string cacheKey);

Examples

  • The following example removes the cache entity based on the entity provided to it. If it exists in the cache, it will be removed.
using (NorthwindContext database = new NorthwindContext())
{
    Customers cust = new Customers
    {
        CustomerId = "HANIH",
        ContactName = "Hanih Moos",
        ContactTitle = "Sales Representative",
        CompanyName = "Blauer See Delikatessen"
    };

    Cache cache = database.GetCache();

    cache.Remove(cust);
}

  • The following example takes cache key as an argument. If an entity against the key exists in cache, it will be removed from the cache.
using (NorthwindContext database = new NorthwindContext())
{
    Cache cache = database.GetCache();

    cache.Remove(cacheKey); //cacheKey saved during Insert()/FromCache()/LoadIntoCache() calls
}

RemoveByQueryIdentifier

The RemoveByQueryIdentifier method removes all entities from the cache based on the specified QueryIdentifier in CachingOptions (when inserting into cache). If entities with the identifier exist, all associated entities are removed from the cache, but not from the actual data source.

using (NorthwindContext database = new NorthwindContext())
{
    CachingOptions options = new CachingOptions
    {
        QueryIdentifier = new Tag("CustomerEntity"),
    };

    Cache cache = database.GetCache(); //get NCache instance

    cache.RemoveByQueryIdentifier(options.QueryIdentifier);

}

Back to top Copyright © 2017 Alachisoft