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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With