7

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

Ghyath Serhal
  • 7,106
  • 6
  • 41
  • 57

3 Answers3

4

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.

Jonas Høgh
  • 9,368
  • 1
  • 21
  • 41
2

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.

Eranga
  • 31,383
  • 5
  • 88
  • 92
2

Using a new context instance per request or action is a must. There is no performance impact on this because metadata (from EDMX) are loaded and compiled only once (first time you need them) and after that the metadata are reused for all instances of the same context until application pool recycles. You can even speed up initialization by precompiling metadata.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654