EntityCollection<TEntity>.Attach 方法

定義

定義兩個相連物體在物件語境中的關係。

多載

名稱 Description
Attach(IEnumerable<TEntity>)

定義物件與物件相關物件集合在物件語境中的關係。

Attach(TEntity)

定義兩個相連物體在物件語境中的關係。

Attach(IEnumerable<TEntity>)

定義物件與物件相關物件集合在物件語境中的關係。

public:
 void Attach(System::Collections::Generic::IEnumerable<TEntity> ^ entities);
public void Attach(System.Collections.Generic.IEnumerable<TEntity> entities);
override this.Attach : seq<'Entity (requires 'Entity : null and 'Entity :> System.Data.Objects.DataClasses.IEntityWithRelationships)> -> unit
override this.Attach : seq<'Entity (requires 'Entity : null)> -> unit
Public Sub Attach (entities As IEnumerable(Of TEntity))

參數

entities
IEnumerable<TEntity>

物件上下文中與來源物件相關的集合。

例外狀況

entities 集合為 null

集合中的 entities 來源物件或物件是否 null 處於 Unchanged OR Modified 狀態。

-或-

這種關係無法根據 EDM 的元資料來定義。 當概念架構中的關聯不支持兩種類型的關係時,這種情況可能發生。

備註

Attach 方法用於定義物件與相關物件集合之間的關係,當來源物件與相關物件集合都已存在於物件上下文中時。 若要附加一個關係已定義的物件或物件圖,請呼叫Attach該方法。ObjectContext 若要建立與來源物件相關的新物件,請呼叫 AddEntityCollection<TEntity> 如需詳細資訊,請參閱附加和移除物件

如果集合已經被填滿或部分填滿,該 Attach 方法會將現有實體與給定實體合併。 所給的實體並不被視為所有相關實體的完整集合。

所有被送入的實體都必須在 Unchanged OR Modified 州。 只有當狀態管理器已經在追蹤關係實例時,才允許物件進入 Deleted 狀態。

適用於

Attach(TEntity)

定義兩個相連物體在物件語境中的關係。

public:
 void Attach(TEntity entity);
public void Attach(TEntity entity);
override this.Attach : 'Entity -> unit
Public Sub Attach (entity As TEntity)

參數

entity
TEntity

被附著的物體。

例外狀況

當 是 entitynull時。

當 無法 entity 與來源物件相關聯時, 當概念架構中的關聯不支持兩種類型的關係時,這種情況可能發生。

-或-

當任一物件處於 null 或不處於 UnchangedModified 狀態時。

範例

此範例基於 Adventure Works 銷售模型。 要執行這個範例中的程式碼,你必須已經將 AdventureWorks 銷售模型加入你的專案,並設定專案使用實體框架。 為此,請完成 如何:手動配置實體框架 Project 以及 如何:手動定義模型與映射檔案中的步驟。

此範例將一組分離SalesOrderDetail物件與一個分離SalesOrderHeader物件附加於物件上下文,然後定義物件與每個SalesOrderDetail物件之間的SalesOrderHeader關係。

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 方法用於定義兩個物件間的關係,當兩個物件已存在於物件語境中。 若要附加一個關係已定義的物件或物件圖,請呼叫Attach該方法。ObjectContext 若要建立與來源物件相關的新物件,請呼叫 AddEntityCollection<TEntity> 如需詳細資訊,請參閱附加和移除物件

如果已經 EntityCollection<TEntity> 載入了物件,該 Attach 方法會將物件與 中 EntityCollection<TEntity>現有的物件合併。

附加物件不假設是所有相關實體物件的完整集合。

與此 EntityCollection<TEntity> 關聯的物件及所有附加物件必須處於 Unchanged or Modified 狀態。

狀態中的 Deleted 物件只有在已經 ObjectStateManager 追蹤該關係實例時才能附加。

適用於