This documentation is archived and is not being maintained.

ObjectContext.Attach Method

Attaches an object or object graph to the object context when the object has an entity key.

Namespace:  System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public void Attach(
	IEntityWithKey entity
)

Parameters

entity
Type: System.Data.Objects.DataClasses.IEntityWithKey

The object to attach.

ExceptionCondition
ArgumentNullException

The entity is null.

InvalidOperationException

Invalid entity key.

Call Attach on the ObjectContext to attach the object to the object context. Do this when the object already exists in the data source but is currently not attached to the context. For more information, see Attaching Objects (Entity Framework).

Attach is used to attach an object or the top-level object in an object graph.

The object being attached must implement IEntityWithKey to expose an EntityKey. All generated entity classes implement IEntityWithKey. If the object is an instance of a custom data class that does not implement IEntityWithKey, you should instead call the AttachTo method to attach the object. For more information, see Implementing Custom Data Class Interfaces (Entity Framework).

When you attach related objects, you must also call Attach on the EntityReference<TEntity> or the EntityCollection<TEntity> to define the relationship. For more information, see Attaching Objects (Entity Framework).

This method calls the AttachTo method.

The following considerations apply when attaching objects:

The example in this topic is based on the Adventure Works Sales Model. In this example, two objects are attached and then the relationship is defined.

private static void AttachRelatedObjects(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder,
    List<SalesOrderDetail> detachedItems)
{
    try
    {
        // Attach the root detachedOrder object to the supplied context.
        currentContext.Attach(detachedOrder);

        // Attach each detachedItem to the context, and define each relationship 
        // by attaching the attached SalesOrderDetail object to the EntityCollection on  
        // the SalesOrderDetail navigation property of the now attached detachedOrder. 
        foreach (SalesOrderDetail item in detachedItems)
        {
            currentContext.Attach(item);
            detachedOrder.SalesOrderDetail.Attach(item);
        }
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.GetType().ToString() + ": " + ex.ToString());
    }
}

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5 SP1
Show: