Does DbContext need MemoryCache or Redis in Net Core?

て烟熏妆下的殇ゞ 提交于 2019-12-25 01:07:19

问题


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:


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.



来源:https://stackoverflow.com/questions/58157908/does-dbcontext-need-memorycache-or-redis-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!