ObjectContext.Attach(IEntityWithKey) Metodo

Definizione

Associa un oggetto o un oggetto grafico al contesto dell'oggetto quando l'oggetto ha una chiave di entità.

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)

Parametri

entity
IEntityWithKey

Oggetto da associare.

Eccezioni

Il entity è null.

Chiave di entità non valida.

Esempio

In questo esempio vengono collegati due oggetti e quindi viene definita la relazione.

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);
    }
}

Commenti

Chiamare Attach su ObjectContext per collegare l'oggetto al contesto dell'oggetto. Eseguire questa operazione quando l'oggetto esiste già nell'origine dati, ma non è attualmente collegato al contesto.

Attach viene utilizzato per associare un oggetto o l'oggetto di primo livello in un oggetto grafico.

L'oggetto associato deve implementare IEntityWithKey per esporre un oggetto EntityKey. Tutte le classi di entità generate implementano IEntityWithKey.

Quando si collegano oggetti correlati, è necessario chiamare Attach anche su EntityReference<TEntity> o per EntityCollection<TEntity> definire la relazione.

Questo metodo chiama il AttachTo metodo .

Quando si collegano oggetti, si applicano le considerazioni seguenti:

  • Se l'oggetto associato ha oggetti correlati, tali oggetti verranno associati anche al contesto dell'oggetto.

  • Gli oggetti vengono aggiunti al contesto dell'oggetto in uno stato invariato.

  • L'oggetto passato al Attach metodo deve avere un valore valido EntityKey . Se l'oggetto non ha un valore valido EntityKey , utilizzare il AttachTo metodo per specificare il nome del set di entità.

Si applica a

Vedi anche