Entity Framework Core (EF Core) is a widely used Object-Relational Mapping (ORM) framework that enables .NET applications to interact with databases using C# objects. However, excessive database queries can lead to performance bottlenecks, making caching a vital optimization strategy.
Key Takeaways
EF Core Limitations: EF Core default caching is limited to the DbContext lifespan (First-Level), meaning data is not shared across different user requests or sessions.
Distributed Second-Level Caching: NCache acts as a distributed Second-Level cache to reduce database trips by sharing cached data across all application instances.
Optimizing Reference Data: Reference data (e.g., product catalogs) that changes infrequently should be cached entirely at startup using the LoadIntoCache method.
Maximizing Query Speed: For critical read operations, queries should run strictly against the cache using FromCacheOnly to ensure maximum speed and zero database latency.
Understanding First-Level vs. Second-Level Caching
EF Core supports two levels of caching:
- First-Level Caching: This is enabled by default and stores query results within the same DbContext instance, reducing redundant queries. However, this cache is cleared when the DbContext instance is disposed.
- Second-Level Caching: This extends caching across multiple DbContext instances by storing frequently accessed data in a shared cache, significantly reducing database calls and improving performance, especially in distributed systems.
| Feature | EF Core First-Level Cache | NCache Second-Level Cache |
| Architecture | In-Process (Local Memory) | Distributed Cluster (Out-of-Proc) |
| Data Visibility | Isolated (Private to Request) | Shared (Accessible by all Users/Servers) |
| Lifespan | Temporary (Cleared on Dispose) |
Persistent (Configurable Expiration) |
| Database Load | Reduces duplicate queries in 1 transaction | Offloads DB across entire application |
| Scalability | None (Local only) | Linear (Adds capacity with nodes) |
| Best For | Short-lived Transactional Data | Reference Data & Product Catalogs |
Benefits of Caching with EF Core
Integrating caching into EF Core applications provides several advantages:
- Faster Data Retrieval – Cached data ensures quicker access to frequently used records.
- Improved Scalability – Reduces database load and supports high-traffic applications.
- Efficient Query Execution – Avoids repetitive database queries, optimizing performance.
Understanding Reference Data
Reference data includes information that remains stable for longer time periods but still requires periodic updates, such as product catalogs, country lists, and configuration settings. Since it is accessed frequently but modified less often, caching reference data significantly improves performance and reduces unnecessary database queries.
For optimal performance, reference data should be cached as complete datasets rather than individual records. This ensures that LINQ queries run efficiently against the cache, providing accurate results without needing database access.
Understanding Reference Data Caching in EF Core
NCache seamlessly integrates with EF Core to optimize reference data caching. Two key methods are LoadIntoCache and FromCacheOnly.
- LoadIntoCache
The LoadIntoCache method should be used to load entire datasets (e.g., all products) into the cache at once. This ensures that applications can later run queries on the cached dataset without requiring further database access.
Example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using (var context = new ApplicationDbContext()) { var cachingOptions = new CachingOptions { StoreAs = StoreAs.SeparateEntities, Priority = CacheItemPriority.High, CreateDbDependency = true }; // Preload the entire 'Products' table into the distributed cache at startup // This ensures reference data is immediately available for high-speed access context.Products.LoadIntoCache(cachingOptions); } |
- FromCacheOnly
After loading the dataset into the cache using LoadIntoCache, you should use the FromCacheOnly method to query data directly from the cache. This prevents unnecessary database queries and ensures fast data retrieval.
Example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using (var context = new ApplicationDbContext()) { var cachingOptions = new CachingOptions { StoreAs = StoreAs.SeparateEntities, Priority = CacheItemPriority.High, CreateDbDependency = true }; // Load the entire product dataset into the cache context.Products.LoadIntoCache(cachingOptions); } |
How to Implement Reference Data Caching in EF Core?
To use NCache for reference data caching in EF Core applications, follow these steps:
- Step 1: Install the NCache EF Core Provider
|
1 |
Install-Package EntityFrameworkCore.NCache |
- Step 2: Configure NCache in Your Application
Modify your DbContext to enable caching:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
[Serializable] public class Product { public int ProductId { get; set; } public string Name { get; set; } public string Category { get; set; } } public class ApplicationDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string cacheId = "myCache"; var options = new CacheConnectionOptions { RetryInterval = TimeSpan.FromSeconds(3), ConnectionRetries = 2, ServerList = new List { new ServerInfo("20.200.20.XX", 9800) }, UserCredentials = new Credentials("username", "password") }; NCacheConfiguration.Configure(cacheId, DependencyType.SqlServer, options); optionsBuilder.UseSqlServer("YourConnectionString"); } } |
Conclusion
By leveraging NCache’s LoadIntoCache and FromCacheOnly methods, EF Core applications can efficiently manage reference data, reducing database load and improving performance. Clearly, implementing these caching strategies ensures faster data retrieval and enhances application scalability.
For more detailed information, refer to the NCache documentation on EF Core caching:
- Entity Framework (EF) Core Cache | NCache Docs
- EF Core Extension Methods | NCache Docs
- NCache Details
- NCache Docs
- NCache Download Center
Frequently Asked Questions (FAQ)
Q: What is the difference between First-Level and Second-Level caching in EF Core?
A: First-Level caching is built into EF Core and stores data only within the current DbContext (request) lifespan. Second-Level caching (like NCache) is distributed, meaning the cached data is shared across all users and applications, persisting beyond a single HTTP request.
Q: When should I use LoadIntoCache vs. FromCacheOnly in NCache?
A: Use LoadIntoCache when you want to read data from the database and populate the cache (often used at application startup). Use FromCacheOnly when you want to retrieve data strictly from the cache to ensure maximum performance, avoiding any database calls.
Q: Does NCache support cache dependencies for EF Core?
A: Yes, NCache supports various dependencies (such as SQL Dependency or Oracle Dependency). This ensures that if data changes in the backend database, the corresponding items in the cache are automatically invalidated or updated to ensure data freshness.

