是的DbContext一个昂贵的操作? [英] Is DbContext an expensive operation?

查看:130
本文介绍了是的DbContext一个昂贵的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中的MVC EF框架中,我看到了很多,简单地创建一个新的的DbContext 每当需要插入或查询,然后关闭/释放它(许多用例使用自动关闭/释放)。

In C# MVC EF framework, I saw lots of examples that simply creates a new DbContext whenever a insert or query is needed, and then close/release it (many use the "using" for auto close/release).

有没有这方面的一些搜索,但没有找到一个很好的答案,而是创建一个的DbContext 一个非常便宜,快捷的操作?

Did some search on this but couldn't find a good answer, but is creating a DbContext a very cheap and fast operation?

例如,考虑一个典型的MVC应用,网页上有许多组件,如标题,代尔棒,主要内容,等等,并且在一个非平凡的设置,每个组件将具有其自己的独立的逻辑和code - 做我想在这些组件来创建一个新的的DbContext ? (如果是,将系统自动缓存查询结果 - 例如,常见的情况是,在这些组件,它需要查询当前站点范围的设置数据库,这是同一行中表)。

For example, thinking about a typical MVC application, on the page it has many "components", such as headers, sider bars, main content, etc., and in a non-trivial setup, each component will have its own individual logic and code -- do I suppose to create a new DbContext in each of these components? (if yes, will the system auto cache the query result? -- for example, an common use case is that, in each of these component, it needs to query the database for current site wide settings, which is the same row in a table).

推荐答案

作为性能注意对于实体框架4,5和6 事项一节9.3(重点煤矿):

As noted in "Performance Considerations for Entity Framework 4, 5 and 6" section 9.3 (emphasis mine):

实体框架的上下文的意思,以提供最优化的性能的经验用作短命实例。 上下文预计将是短暂的和丢弃,因此已实施是非常轻便,再利用元数据只要有​​可能。在网络情况下它记住这一点,并没有上下文比单个请求的持续时间更重要。同样,在非Web场景,背景应该根据你的实体框架不同级别缓存的理解丢弃。 一般而言,应避免有一个上下文实例整个应用程序的生命,以及每个线程上下文和语境静态

Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.

这篇关于是的DbContext一个昂贵的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆