Compartir a través de


Cómo asociar objetos relacionados (Entity Framework)

En este tema, se proporcionan ejemplos de cómo asociar objetos relacionados a un contexto del objeto. Para obtener más información, vea Asociar objetos (Entity Framework). Este procedimiento se usa al reconstruir un gráfico de objetos que se serializó con la serialización XML.

El ejemplo de este tema se basa en el modelo Adventure Works Sales. Para ejecutar el código de este ejemplo, debe haber agregado el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para que use Entity Framework. Para ello, complete los procedimientos de Cómo configurar manualmente un proyecto de Entity Framework y Cómo definir manualmente un modelo Entity Data Model (Entity Framework).

Ejemplo

En este ejemplo, se asocia una colección de objetos SalesOrderDetail desasociados y un objeto SalesOrderHeader desasociado a un contexto del objeto y, a continuación, se definen las relaciones entre el objeto SalesOrderHeader y cada uno de los objetos SalesOrderDetail.

Private Shared Sub AttachRelatedObjects( _
ByVal currentContext As ObjectContext, _
ByVal detachedOrder As SalesOrderHeader, _
ByVal detachedItems As List(Of SalesOrderDetail))
    Try
        ' Attach the root detachedOrder object to the supplied context.
        currentContext.Attach(detachedOrder)

        ' Attach each detachedItem to the context, and define each relationship
        ' by attaching the attached SalesOrderDetail object to the EntityCollection on 
        ' the SalesOrderDetail navigation property of the now attached detachedOrder.
        For Each item As SalesOrderDetail In detachedItems
            currentContext.Attach(item)
            detachedOrder.SalesOrderDetail.Attach(item)
        Next

    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Sub
private static void AttachRelatedObjects(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder,
    List<SalesOrderDetail> detachedItems)
{
    try
    {
        // Attach the root detachedOrder object to the supplied context.
        currentContext.Attach(detachedOrder);

        // Attach each detachedItem to the context, and define each relationship
        // by attaching the attached SalesOrderDetail object to the EntityCollection on 
        // the SalesOrderDetail navigation property of the now attached detachedOrder.
        foreach (SalesOrderDetail item in detachedItems)
        {
            currentContext.Attach(item);
            detachedOrder.SalesOrderDetail.Attach(item);
        }
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.GetType().ToString() + ": " + ex.ToString());
    }
}

En este ejemplo, se agrega una colección de objetos SalesOrderDetail desasociados a un objeto SalesOrderHeader desasociado y, a continuación, se asocia este gráfico de objetos al contexto del objeto.

Private Shared Sub AttachObjectGraph( _
ByVal currentContext As ObjectContext, _
ByVal detachedOrder As SalesOrderHeader, _
ByVal detachedItems As List(Of SalesOrderDetail))
    Try
        ' 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.SalesOrderDetail.Add(item)
        Next

        ' Attach the object graph to the supplied context.
        currentContext.Attach(detachedOrder)

    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Sub
private static void AttachObjectGraph(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder, 
    List<SalesOrderDetail> detachedItems)
{
        try
        {
            // 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.SalesOrderDetail.Add(item);
            }

            // Attach the object graph to the supplied context.
            currentContext.Attach(detachedOrder);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.GetType().ToString() + ": " + ex.ToString());
        }
}

Vea también

Conceptos

Serializar objetos (Entity Framework)
Servicios web y Entity Data Model (escenarios de aplicación)

Otros recursos

Administrar el contexto del objeto (Entity Framework)
Trabajar con objetos (tareas de Entity Framework)