EntityCollection<TEntity>::Attach Method (TEntity)
Defines a relationship between two attached objects in an object context.
Assembly: System.Data.Entity (in System.Data.Entity.dll)
| Exception | Condition |
|---|---|
| ArgumentNullException | When the entity is null. |
| InvalidOperationException |
The Attach method is used to define relationships between two objects when both objects already exist in the object context. To attach an object or an object graph where the relationships are already defined, call the Attach method on the ObjectContext. To create a new object that is related to the source object, call the Add method on the EntityCollection<TEntity>. For more information, see Attaching and Detaching Objects.
If the EntityCollection<TEntity> already has loaded objects, the Attach method merges the object together with the existing objects in the EntityCollection<TEntity>.
The attached object is not assumed to be the complete set of related entity objects.
The object associated with this EntityCollection<TEntity> and all objects being attached to it must be in an Unchanged or Modified state.
Objects in the Deleted state can only be attached when the ObjectStateManager is already tracking the relationship instance.
This example is based on the . To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files.
This example attaches a collection of detached SalesOrderDetail objects and a detached SalesOrderHeader object to an object context, and then defines the relationships between the SalesOrderHeader object and each SalesOrderDetail object.
Available since 3.5