Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing the entity framework objectcontext on every call

I have a web application that uses Entity framework as a data access layer. Now I am initializing the entity class that inherit from ObjectContext on each request.

I just want to know if there are any disadvantages or consequences from a performance point of view of doing this. Is it better to cache this object.

Note that i have large edmx files, some contains about 50 tables

like image 402
Ghyath Serhal Avatar asked May 10 '11 09:05

Ghyath Serhal


2 Answers

Initializing an ObjectContext per request is probably the most common way to implement EF in a web application. It is not a performance issue to do so, the initialization is quite cheap. The ObjectContext is EF's implementation of the Unit of Work pattern, and therefore it is a good practice to encapsulate conversations with the database in a single unit of work. Caching the ObjectContext across requests can be problematic since long running database conversations are not easily handled in web applications, as you never know when the next request from a given client will be arriving.

like image 54
Jonas Høgh Avatar answered Oct 14 '22 14:10

Jonas Høgh


It is the recommended practice when dealing with Entity Framework in Web applications.

However you can partition your context containing 50 tables to couple of contexts if you can divide your tables into independent areas. Then it will be much easier for you to manage the contexts.

Caching the Context is not recommended. ObjectContext is not thread safe. IT will also violate Unit of work pattern. This will lead to unwanted behavior such as commiting changes of multiple users in a single transaction.

like image 30
Eranga Avatar answered Oct 14 '22 13:10

Eranga