Detaching Objects (Entity Framework)

The Entity Framework supports scenarios that require a long-running object context. For example, you might find this scenario in a Windows application where data objects are bound to a visual control, and objects must be persisted while the data is displayed in the control. When a query is executed within an object context, the returned objects are automatically attached to the context. This means that executing repeated queries in the same object context will increase the memory requirements of the object context. The exception is when a query is executed with a MergeOption value of NoTracking. In this case, objects are not attached to the object context.

Object Services lets you detach objects from an object context. When the objects are no longer required, they can be detached. Detached objects are not referenced by the object context, and their resources can be reclaimed by the .NET Framework.

To detach objects, you call the Detach method and pass a reference to the object being detached, as in the following example:

' Detach the first SalesOrderDetail in the collection.
context.Detach(order.SalesOrderDetail.First())
// Detach the first SalesOrderDetail in the collection.
context.Detach(order.SalesOrderDetail.First());

The following considerations apply when detaching objects:

  • Detach only affects the specific object passed to the method. If the object being detached has related objects in the object context, those objects are not detached.

  • Relationship information is not maintained for a detached object.

  • Object state information is not maintained when an object is detached. This includes tracked changes and temporary key values.

  • Detaching objects does not affect data in the data source.

  • Cascade delete directives and referential constraints are not enforced during a detach operation.

  • The benefits of detaching objects should be considered against the additional processing required to perform the operation. When the scope of the user data has changed, such as displaying a new form with a different set of data, you should consider creating a new ObjectContext instance, rather then just detaching objects from an existing ObjectContext.

For more information, see How to: Detach Objects from an Object Context (Entity Framework).

See Also

Concepts

Attaching Objects (Entity Framework)

Other Resources

Managing the Object Context (Entity Framework)