如何:附加相关对象(实体框架)

本主题提供有关如何将相关对象附加到对象上下文的示例。 有关更多信息,请参见附加和分离对象(实体框架)。 本主题中的示例基于 Adventure Works 销售模型。 若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架 。 为此,请完成如何:手动配置实体框架项目如何:手动定义模型和映射文件(实体框架)中的过程。

示例

本示例将已分离的 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);
}

另请参见

概念

序列化对象(实体框架)
生成 N 层应用程序(实体框架)