Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DbContext an expensive operation?

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

like image 676
jjw2015 Avatar asked Aug 29 '15 05:08

jjw2015


2 Answers

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.

like image 187
Jeroen Vannevel Avatar answered Nov 02 '22 14:11

Jeroen Vannevel


You could use injection, like through Unity, which would allow a single instance of the DbContext to be created when the request comes in and inject that where it's needed. With Unity I believe you can specify whether a single instance is created per request or whether a new one gets created every time.

It's not massively slow to create the DbContext wherever you need it, but this comes with a little common sense, so reuse one you already have if you can and if you're concentrating on performance in relation to database queries then there will always be an overhead to using any ORM. It's a convenience trade off.

I'd also suggest using something like Glimpse which allows you to see all the queries and connections that were used rendering the page, including ajax queries and gives you a great overview of what's going on. Can be a bit scary sometimes!

like image 25
Daniel Abbatt Avatar answered Nov 02 '22 14:11

Daniel Abbatt