如何使实体框架缓存某些对象缓存、实体、框架、对象

2023-09-02 01:44:01 作者:\\ 绕指轻烟

我使用实体框架。

在我的数据库中存储其来源的人员和国家。当我加载一个Person对象我wan't知道什么是每个人起源的地方。有没有办法缓存的国家列表中,这样就不会出现不必要的请求。

In my database are stored persons and country of their origins. When I'm loading a person object I wan't to know what is the place each person originates. Is there a way to cache list of countries so that there wouldn't be unnecessary requests.

推荐答案

由于卢曼已经说我的队友亚雷克有极好的样本缓存提供商实体框架。其中他谈到here.

As Luhmann has already said my mate Jarek has an excellent sample Caching provider for the Entity Framework. Which he talks about here.

不过有时这种做法是矫枉过正,我怀疑缓存的国家就是一个很好的例子,这种努力是不值得的。它可能更好地执行某种形式的临时缓存。

However sometimes this approach is overkill, and I suspect that caching countries is a good example where the effort isn't worth it. It maybe better to implement some sort of ad-hoc caching.

如果您尝试这样做的主要问题你会遇到的是一个实例实体框架的实体只能连接到一个ObjectContext的的时间,这意味着如果你得到并发请求(如在一个网站),你将有问题的是你随意在高速缓存中的项目,并利用它们盲目地。

If you try to do this the main problem you will run into is that an instance Entity Framework entity can only be attached to one ObjectContext at a time, which means if you are getting concurrent requests (like in a website) you will have problems is you just grab items from the cache and use them blindly.

您需要的是一个克隆缓存,即所以当你抓住的东西从缓存其复制它们。

What you need is a cloning cache, i.e. so when you grab something from the cache it clones them.

我把一个提示,说明如何做到这一点Tip 14 - 如何缓存实体框架参考数据

I put together a tip that illustrates how to do this Tip 14 - How to cache Entity Framework Reference Data

希望这有助于

亚历克斯·詹姆斯

实体框架团队微软。