Redigera

Dela via


ObjectContext.Attach(IEntityWithKey) Method

Definition

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

public:
 void Attach(System::Data::Objects::DataClasses::IEntityWithKey ^ entity);
public void Attach (System.Data.Objects.DataClasses.IEntityWithKey entity);
member this.Attach : System.Data.Objects.DataClasses.IEntityWithKey -> unit
Public Sub Attach (entity As IEntityWithKey)

Parameters

entity
IEntityWithKey

The object to attach.

Exceptions

The entity is null.

Invalid entity key.

Examples

In this example, two objects are attached and then the relationship is defined.

private static void AttachRelatedObjects(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder,
    List<SalesOrderDetail> detachedItems)
{
    // 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.SalesOrderDetails.Attach(item);
    }
}

Remarks

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 Customizing Objects.

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.

When you attach related objects, you must also call Attach on the EntityReference<TEntity> or the EntityCollection<TEntity> to define the relationship.

This method calls the AttachTo method.

The following considerations apply when attaching objects:

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

  • Objects are added to the object context in an unchanged state.

  • 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.

Applies to

See also