Does DbContext need MemoryCache or Redis in Net Core?

.net .net-core asp.net-core c# entity-framework-core

Question

We have multiple lookup tables in a SQL Server database. Tables are used in application dropdown menus.

AddressType:

  • Home
  • Business

ProductType:

  • Books
  • Food
  • Electronics

Instead of continually reading database lookup tables, team wants to apply MemoryCache or Redis Cache (to reduce database load, and increase in-memory performance). However, we learned that Entity Framework Core DbContext already has caching.

So in this case, would there be any value in caching looking tables, if after a certain amount of reads, the DbContext does this already? Would adding more caching code for MemoryCache/Redis over DbContext help? Or would it be an unnecessary layer?

1
0
10/6/2019 7:51:16 PM

Popular Answer

As with Microsoft is EF Core 2.0, EF Core supports only First-Level Cache, that is, when an entity is materialized as the result of executing a query, it is stored in an in-memory cache associated with the Entity Framework Context ( a.k.a System.Data.Entity.DbContext class )

EF Core’s first level caching mechanism provides some performance boost, however, consider a scenario where the entity’s record changes in the database level and we are still working off of locally cached copies of entities from the Entity Framework context. so this leads to a situation where we will get an incorrect result set.

So a workaround for this problem is to detach those entities from the context, which effectively means removing it from first-level cache, also termed as eviction of the cached item. Once detachment is done, entities may be fetched once again, which would ensure that fresh data is read from the database.

So, we see that EF Core’s out of the box (OOB) first-level caching mechanism is far from perfect. It leads to clunky code which is prone to errors and there is fairly a good chance of the code base becoming convoluted and unmaintainable in the long run. A few of the other drawbacks of EF Core OOB first-level caching mechanism are:

  • As more objects and their references are loaded into memory, the memory consumption of the context may increase exponentially – ironically leading to performance issues, for which we had started using EF core first-level cache in the first place.
  • Possible memory leaks when disposal of context not done properly when it is not required.
  • The probability of running into concurrency related issues increases as the gap between the time when the data is queried and updated grows.

So as you can see given the need of scaling for Distributed applications , it is highly recommended to go for usage of Caching Providers.

1
9/30/2019 7:05:00 AM


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