DbContext是否昂贵? [英] Is DbContext an expensive operation?

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

问题描述

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



做了一些搜索,但找不到一个很好的答案,但是正在创建一个非常便宜的 DbContext 并快速运行?



例如,考虑一个典型的MVC应用程序,在页面上有许多组件,如标题,框架栏,主要内容等,以及一个不平凡的设置,每个组件都有自己的单独的逻辑和代码 - 我想在每个组件中创建一个新的 DbContext ? (如果是,系统会自动缓存查询结果吗?例如,一个常见的用例是,在这些组件的每个组件中,它需要查询数据库当前的站点宽度设置,这是一个

解决方案

实体框架4,5和6的性能注意事项9.3节(强调我的):



< blockquote>

实体框架的上下文旨在作为短期实例,以提供最佳的性能体验。 上下文预计将是短暂的和被丢弃的,因此已被实现为非常轻量级,并尽可能重用元数据。在网络场景中,记住这一点非常重要,并且没有一个上下文超过单个请求的持续时间。同样,在非Web方案中,应根据对实体框架中不同缓存级别的理解,丢弃上下文。一般来说,应该避免在应用程序的整个生命周期中使用上下文实例,以及每个线程和静态上下文的上下文。



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).

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

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).

解决方案

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

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天全站免登陆