Udostępnij za pośrednictwem


Attaching and Detaching Objects

In the Entity Framework, objects can be attached to or detached from an object context. Objects that are attached to an object context are tracked and managed by that object context. Detached objects are not referenced by the object context, and their resources can be reclaimed by the .NET Framework. This topic describes how to attach and detach objects and some considerations for doing so.

Attaching Objects

When a query is executed inside an object context in the Entity Framework, the returned objects are automatically attached to the object context. You can also attach objects to an object context that are obtained from a source other than a query. You might attach objects that have been previously detached, objects that have been returned by a NoTracking query, or objects that have been obtained outside the object context. You can also attach objects that have been stored in the view state of an ASP.NET application or have been returned from a remote method call or Web service.

Use one of the following methods to attach the object to an object context:

Member Description

System.Data.Objects.ObjectSet.AddObject(

or

System.Data.Objects.ObjectContext.AddObject(System.String,System.Object)

Adds an object and its related objects to the ObjectContext and sets the entity objects to the Added state. In this state, the entity objects are not required to have unique key values. The temporary key values are assigned to key properties and are updated with the data source-generated values after you save the objects. After you have added the objects, change the state of the entity objects appropriately.

System.Data.Objects.ObjectSet.Attach(

or

System.Data.Objects.ObjectContext.Attach(System.Data.Objects.DataClasses.IEntityWithKey)

and

AttachTo

Adds an object to the ObjectContext and sets the object to the Unchanged state. In the Unchanged state, the Entity Framework treats the entity key values as final. If more than one entity of a particular type has the same key value, the Entity Framework will throw an exception. To avoid getting the exception, use the AddObject method to attach the detached objects and then change the state appropriately.

Objects are attached to the object context in an Unchanged state. If you need to change the state of an object or the relationship because you know that your object was modified in detached state, use one of the following methods.

Member Description

ChangeObjectState

Changes an entity or relationship to a new state (such as Added or Modified). This change may have an impact on the relationships that an entity participates in. For example, moving an entity to the Added state will also move any unchanged relationships to the Added state. Similarly, marking an entity as Modified will mark all scalar values as Modified.

You may also use the ChangeState method of the ObjectStateEntry.

ChangeRelationshipState

Changes the existing relationship between two entities to the specified state. If there is no relationship between the entities, this method will create a new one in the specified state. This method is not supported for relationships based on a foreign key association. For more information, see Defining and Managing Relationships.

You may also use the ChangeObjectState method of the ObjectStateEntry.

ChangeState

This method behaves the same as ChangeObjectState or ChangeRelationshipState depending on whether the ObjectStateEntry is an object or a relationship.

SetModifiedProperty

Sets individual properties to the Modified state. Use this method when you know what properties were modified instead of setting the whole entity to modified.

If the object being attached has updated property values, use one of the following methods:

Member Description

System.Data.Objects.ObjectSet.ApplyCurrentValues(

or

System.Data.Objects.ObjectContext.ApplyCurrentValues.String,

Copies the scalar values from the supplied object into the object in the ObjectContext that has the same key. Any values that differ from the original values will be marked as modified.

If you have a graph with current values and want to apply the original values, call ApplyOriginalValues method.

You may also use the ApplyCurrentValues method of the ObjectStateEntry.

System.Data.Objects.ObjectSet.ApplyOriginalValues(

or

System.Data.Objects.ObjectContext.ApplyOriginalValues.String,

Copies the scalar values from the supplied object into set of original values for the object in the ObjectContext that has the same key. Any values that differ from the current values will be marked as modified.

You may also use the ApplyOriginalValues method of the ObjectStateEntry.

SetModifiedProperty

Sets individual properties to the Modified state. Use this property when you know what properties were modified instead of setting the whole entity to modified.

GetUpdatableOriginalValues

Gets the OriginalValueRecord instance that represents the updatable version of the original values of the object that is associated with this ObjectStateEntry. Use the returned OriginalValueRecord instance to read or update the original properties of the object individually.

CurrentValues

Gets the CurrentValueRecord instance that represents the current values of the object that is associated with this ObjectStateEntry. Use the returned CurrentValueRecord instance to read or update the current properties of the object individually.

Considerations for Attaching Objects

The following considerations apply when attaching objects to the object context:

  • If the object being attached has related objects, those objects are also attached to the object context.

  • If the attached object does not exist in the data source, it is not added during SaveChanges. In this case, when changes are made to properties, an exception occurs at the server during SaveChanges. To add an object, use System.Data.Objects.ObjectSet.AddObject( or System.Data.Objects.ObjectContext.AddObject(System.String,System.Object)

    If the object being attached is related to other objects, you must explicitly define the relationships in one of the ways that are described in Defining and Managing Relationships. For more information, see How to: Attach Related Objects.

  • The object that is passed to the Attach method must have a valid EntityKey value. If the object does not have a valid EntityKey value, use the AttachTo method to specify the name of the entity set.

  • An InvalidOperationException occurs when an object being attached has the same EntityKey as a different object already present in the object context. This error does not occur if an object in the context with same key but is in the Added state.

Detaching Objects

In Entity Framework applications, you can detach objects from the object context. You might detach objects to conserve resources, as executing repeated queries in the same object context increases the memory requirements of the object context. You can keep objects from being attached to the object context by executing a query with a MergeOption value of NoTracking, or you can detach them by calling the System.Data.Objects.ObjectSet.Detach( or System.Data.Objects.ObjectContext.Detach(System.Object) method and passing a reference to the object being detached, as in the following example:

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

Considerations for Detaching Objects

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.

  • In an independent association, the 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 in an identifying relationship 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 than just detaching objects from an existing ObjectContext.

For more information, see How to: Detach Objects from an Object Context.

In This Section

How to: Attach Related Objects

How to: Apply Changes Made to a Detached Object

How to: Detach Objects from an Object Context

See Also

Concepts

Building N-Tier Applications