ObjectContext.Attach(IEntityWithKey) 方法

定義

當物件具有實體索引鍵時,將物件或物件圖形附加至物件內容。

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)

參數

entity
IEntityWithKey

要附加的物件。

例外狀況

entitynull

無效的實體索引鍵。

範例

在這個範例中,我們將附加兩個物件,然後定義其關聯性。

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

備註

您可以在 Attach 上呼叫 ObjectContext,以便將此物件附加到物件內容。 請於此物件已經在資料來源中但目前未附加到此內容時執行此動作。 如需詳細資訊,請參閱 自定義物件

Attach 用於附加物件圖形中的物件或最上層物件。

所附加的物件必須實作 IEntityWithKey 來公開 (Expose) EntityKey。 所有產生的實體類別都會實作 IEntityWithKey

附加相關物件時,您也必須呼叫 AttachEntityReference<TEntity>EntityCollection<TEntity> 來定義關聯性。

這個方法會呼叫 AttachTo 方法。

下列考量適用於附加物件時:

  • 如果所附加的物件有相關物件,這些物件也會附加到物件內容。

  • 物件會加入至處於未變更狀態中的物件內容。

  • 傳遞給 Attach 方法的物件必須具有有效的 EntityKey 值。 如果此物件的 EntityKey 值無效,請使用 AttachTo 方法來指定實體集的名稱。

適用於

另請參閱