views:

117

answers:

2

Hello,

While using .NET 3.5 SP1 in ASP.NET MVC application, the ObjectContext can have lifetime on one Http Request OR of a SINGLE method.

using (MyEntities context =  new MyEntities ())
{
//DO query etc
}

How much is increased performance cost of creating ObjectContext in every method VS per request ?

Thanks.

A: 

Is the underlying model small or large, simple or complex? The cost of initializing and using a new objectcontext grows with the size and complexity of the model. If you have a handful of entities, it is usually neglectable. If you have hundreds of entities then it can be significant.

See:
http://oakleafblog.blogspot.com/2008/08/entity-framework-instantiation-times.html
and
http://blogs.msdn.com/adonet/archive/2008/06/20/how-to-use-a-t4-template-for-view-generation.aspx

KristoferA - Huagati.com
+1  A: 

The cost of creating the context is very low. However, using a new context means that you don't have any cached queries from previous contexts. You can work around this to some degree with view generation or CompiledQuery. See also Performance Considerations for Entity Framework Applications

On the other hand, keeping a context around for a long time means you are tracking increasing amounts of state information, which has a performance cost of its own.

In my opinion, however, the most significant cost of a context is code complication. Using multiple contexts tends to lead to confusing code. So I try to use one context per group of related operations, e.g. handling a single HTTP request.

Craig Stuntz