.net 如何让实体框架缓存一些对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1147681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:02:45  来源:igfitidea点击:

How to make Entity Framework cache some objects

.netentity-frameworkentity

提问by Eugeniu Torica

I'm using Entity Framework.

我正在使用实体框架。

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.

在我的数据库中存储了人员和他们的原籍国。当我加载一个 person 对象时,我不想知道每个人起源的地方是什么。有没有办法缓存国家列表,这样就不会出现不必要的请求。

回答by Alex James

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

正如 Luhmann 已经说过的,我的伙伴 Jarek 有一个出色的实体框架示例缓存提供程序。他在这里谈论的。

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.

然而有时这种方法是矫枉过正的,我怀疑缓存国家是一个很好的例子,其中的努力是不值得的。实施某种临时缓存可能会更好。

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.

如果您尝试这样做,您将遇到的主要问题是实例实体框架实体一次只能附加到一个 ObjectContext,这意味着如果您收到并发请求(如在网站中),您将遇到问题您只需从缓存中获取项目并盲目使用它们。

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

您需要的是克隆缓存,也就是说,当您从缓存中获取某些内容时,它会克隆它们。

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

我整理了一个技巧来说明如何做到这一点技巧 14 - 如何缓存实体框架参考数据

Hope this helps

希望这可以帮助

Alex James

亚历克斯·詹姆斯

Entity Framework Team Microsoft.

实体框架团队 Microsoft。

回答by Luhmann

You could take a look at Jaroslaw Kowalski's excellent tracing and caching provider wrappers for Entity Framework.

您可以查看 Jaroslaw Kowalski为 Entity Framework编写的出色的跟踪和缓存提供程序包装器

回答by user134706

I would cache that country list first and assign the appropriate country to each retrieved person. If you decide to also cache persons you should make them depend on the cached countries and invalidate them when you make any update to the countries/country list.

我会先缓存该国家/地区列表,然后为每个检索到的人分配适当的国家/地区。如果您决定还缓存人员,则应使他们依赖于缓存的国家/地区,并在对国家/国家/地区列表进行任何更新时使他们无效。