Using a L2 cache with entity framework

Entity framework has no native support for L2 caching. One approach to reduce amount of repetitive requests is to manually store objects that have already been loaded in a local or distributed cache like redis.

A layer 2 database cache at the DbContext level actually store reference of objects retrieved from the database and will avoid useless roundtrips to the database. This can reduce the amount of requisitions to your database and increase overall performance of your application.

There is no native support, but there is efcache.

Install-Package EntityFramework.Cache


How does this works?

When building a query for your dbcontext, you are actually building an expression tree that describe your query.  Before your query goes to the database, the expression tree is compiled and then sent to the database.

EFcache uses a custom transaction interceptor, intercepts the query before it goes to the database, evaluate que expression tree and check if it already has result for that query. If it does not know the query, it sends it to the database, add the result to its cache, and return the result.

Next time you request the same query; result will come from the cache.


Distributed environment


If you have any system other than your app using your database, or if your application is distributed, you cannot use the library as is. Any changes to the database will not be reflected inside your cache as it is “InMemory”.

However, you can easily replace the built-in Inmemory cache of the library with a Redis cache implementation, or use this library


Submit a Comment

Your email address will not be published. Required fields are marked *

Share This