共用方式為


HOW TO:附加相關的物件 (Entity Framework)

本主題提供的範例會示範如何將相關物件附加到物件內容。 如需詳細資訊,請參閱附加及中斷連結物件。 本主題的範例是根據 Adventure Works Sales Model。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework 。 若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:手動定義模型和對應檔 (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-Tier 應用程式