Share via


How to: Attach Related Objects

This topic provides examples of how to attach related objects to an object context. For more information, see Attaching and Detaching Objects. The example in this topic is based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files.

Example

This example adds a collection of detached SalesOrderDetail objects to a detached SalesOrderHeader object and then attaches this object graph to the object context.

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

See Also

Concepts

Serializing Objects
Building N-Tier Applications