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

備註

呼叫 AttachObjectContext 物件附加到物件上下文中。 當物件已經存在於資料來源中,但目前還沒附加到上下文時,請執行此操作。 欲了解更多資訊,請參閱 「自訂物件」。

Attach 用於附加物件或物件圖中的頂層物件。

被附加的物件必須實作 IEntityWithKey 才能暴露一個 EntityKey。 所有產生的實體類別都實作 IEntityWithKey了 。

當你附加相關物件時,也必須呼叫 AttachEntityReference<TEntity>EntityCollection<TEntity> 定義關係。

此方法呼叫 方法 AttachTo

在附加物件時需考慮以下事項:

  • 如果被附加的物件有相關物件,這些物件也會附加到物件上下文中。

  • 物件會以不變的狀態加入物件上下文。

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

適用於

另請參閱