関連するオブジェクトをアタッチする方法 (Entity Framework)

このトピックでは、関連するオブジェクトをオブジェクト コンテキストにアタッチする方法について説明します。 詳細については、「オブジェクトのアタッチとデタッチ (Entity Framework)」を参照してください。 The example in this topic is based on the Adventure Works Sales Model. この例のコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、Entity Framework が使用されるようにプロジェクトを構成しておく必要があります。 To do this, complete the procedures in Entity Framework プロジェクトを手動で構成する方法 and 方法: モデル ファイルとマッピング ファイルを手動で定義する (Entity Framework).

この例では、デタッチされた SalesOrderDetail オブジェクトのコレクションをデタッチされた SalesOrderHeader オブジェクトに追加して、このオブジェクト グラフをオブジェクト コンテキストにアタッチします。

Private Shared Sub AttachObjectGraph(ByVal currentContext As ObjectContext, ByVal detachedOrder As SalesOrderHeader, ByVal detachedItems As List(Of SalesOrderDetail))
    ' Define the relationships by adding each SalesOrderDetail 
    ' object in the detachedItems List<SalesOrderDetail> collection to the 
    ' EntityCollection on the SalesOrderDetail navigation property of detachedOrder. 
    For Each item As SalesOrderDetail In detachedItems
        detachedOrder.SalesOrderDetails.Add(item)
    Next

    ' Attach the object graph to the supplied context. 
    currentContext.Attach(detachedOrder)
End Sub
private static void AttachObjectGraph(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder,
    List<SalesOrderDetail> detachedItems)
{
    // Define the relationships by adding each SalesOrderDetail 
    // object in the detachedItems List<SalesOrderDetail> collection to the 
    // EntityCollection on the SalesOrderDetail navigation property of detachedOrder.
    foreach (SalesOrderDetail item in detachedItems)
    {
        detachedOrder.SalesOrderDetails.Add(item);
    }

    // Attach the object graph to the supplied context.
    currentContext.Attach(detachedOrder);
}

参照

概念

オブジェクトのシリアル化 (Entity Framework)
N 層アプリケーションのビルド (Entity Framework)