Sunday, April 8, 2012

Optimizing the ObjectContext Lifetime

Optimizing the ObjectContext Lifetime
Microsoft positions EF as a replacement for ADO.NET DataSets, but EF doesn ’ t support occasionally
connected user scenarios with disconnected operations, which is one of the DataSet ’ s primary features.
When users make changes to a DataSet while offline (disconnected from the data source), the changes
are stored in XML UpdateGrams within the DataSet ’ s appropriate table group. When the user reconnects
and executes the DataSet .ApplyChanges() method, updates, or deletions that don ’ t encounter
exceptions, update the underlying tables. EF ’ s DataContext is associated with a DbConnection object,
which the DataContext opens to retrieve or update data and closes immediately thereafter. Disposing
the DataContext closes the connection and disposes all attached objects.
Deciding the optimum ObjectContext lifetime for a specific project or category of projects isn ’ t easy,
because the EF team ’ s members haven ’ t published official guidance for the topic. In addition, the
performance hit and database load for creating an ObjectContext from scratch depends largely on the
number of EntityType s in your EDM and the size of their EntitySet s. Daniel Simmons, EF ’ s
development lead, suggested “ using a single context (or one per thread if your app is multi - threaded) ”
in a March 2008 blog post. In a February 2008 post ( blogs.msdn.com/dsimmons/
archive/2008/02/17/context - lifetimes - dispose - or - reuse.aspx ), Simmons recommended:
·         Add large numbers of new entities to the persistence store in batches; don ’ t attempt to load, for
                example, 200,000 entities in a single transaction.
  • ·         Create a new ObjectContext on each Web service request or Web page post to keep the service or project stateless.
  • ·         Minimize load on the database by Windows form applications by caching slowly changing lookup tables locally, keeping the ObjectContext open for the entire session, and performing a refresh operation on lookup data periodically to prevent stale data from associations.
  • ·         For combinations of transient and static data, maintain the static data in an open ObjectContext and periodically refresh it, but detach the transient data.

You can ’ t serialize the ObjectContext to persist it to an ASP.NET page ’ s ControlState or application ’ s
SessionState property, but you can persist EntityObject instances without associated data to local  caches. The .NET 3.5 SP1 version of the DataContractSerializer lets you persist object graphs that
include cyclic relationships to XML streams for Web services or local XML files for persistence.

No comments:

Post a Comment