This documentation is archived and is not being maintained.

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.


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

    // Attach the object graph to the supplied context.

See Also