• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • .NET Third Party Integrations
  • Entity Framework (EF) Core
  • EF Core Extension Methods
  • Cache Handle
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

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:

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

NCache provides the following APIs for caching purposes:

  1. Insert
  2. Remove
  3. RemoveByQueryIdentifier

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 is SeparateEntities, 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 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

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 CustomerEntity to the cache with Query identifier CustomerEntity and the 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
}

  • This example caches the same entity being inserted into the database:
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

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 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 to 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 (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);
}

  • The following example takes the cache key as an argument. If an entity against the key exists in the cache, it will be removed from the cache.
using (var 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 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

NCache provides a sample application for EF Core on GitHub.

See Also

.NET: Alachisoft.NCache.EntityFrameworkCore and Alachisoft.NCache.Runtime.Caching namespaces.

In This Article
  • EF Core Context: Get Cache Instance
  • Insert
    • Examples
  • Remove
    • Examples
  • RemoveByQueryIdentifier
  • Sample Code
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top