Do we need external caching mechanism while EF 6 use caching out of the box?

asp.net c# caching entity-framework entity-framework-6

Accepted Answer

Because of a number of factors, the fact that EF caches entities in context is in no way a substitute for "actual" cache.

  1. Because EF context represents a unit of work and should be utilised in accordance with this pattern, you shouldn't reuse it for more than one logical action. In a multi-threaded environment, such as a web server application, even if you for some reason reuse context in many actions, you definitely cannot do so.

  2. It does not stop you from querying your database more than once for the same information, for instance:

    var entity1 = ctx.Entities.Where(c => c.Id == 1).First();
    var entity2 = ctx.Entities.Where(c => c.Id == 1).First();
    

    Even if the query is the same and returns the same object, this will nevertheless send two requests to your database. Therefore, nothing is "cached" in the conventional sense here. Observe, however, that even if a database entry has changed between two searches, both will return the same entity. That is what EF context "caching" refers to. It will do the database query again, but the second time it will discover that the context already has an object with the same key when processing the results. It will thus disregard any new values (if any) supplied by the second query and instead return this already-existing ("cached") object. This behaviour is just another reason not to reuse the context across different processes (though you should not do it anyway).

Therefore, you must employ second-level caching in whichever way best meets your requirements if you want to lessen the strain on your database (from simple InMemoryCache to caching EF provider to distributed memcached instance).

4
3/18/2017 11:52:56 AM

Popular Answer

Only the first level cache for entities is implemented by EF; it keeps the entities that have been obtained over the lifetime of a context and returns the entity from context when you request it a second time. A second level cache is what you need, however EF does not install this capability. For instance, NCache provides an excellent caching architecture and comes preconfigured as a second level cache provider for EF. Not the open source version.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow