Поделиться через


Как присоединить связанные объекты (платформа Entity Framework)

В настоящем разделе приведены примеры того, как присоединить связанные объекты к контексту объекта. Дополнительные сведения см. в разделе Присоединение объектов (платформа Entity Framework). Эта процедура используется при реконструкции графа объектов, который был сериализован с использованием языка XML.

Пример в этом разделе основан на модели Adventure Works Sales. Чтобы запустить код, используемый в данном примере, нужно сначала добавить к проекту модель AdventureWorks Sales и настроить его для использования платформы Entity Framework. Для этого выполните инструкции из разделов Как вручную настроить проект Entity Framework и Как определить модель EDM вручную (платформа Entity Framework).

Примеры

В этом примере коллекция отсоединенных объектов SalesOrderDetail и отсоединенный объект SalesOrderHeader присоединяются к контексту объекта, а затем определяются связи между объектом SalesOrderHeader и каждым из объектов 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());
    }
}

В этом примере коллекция отсоединенных объектов SalesOrderDetail добавляется к отсоединенному объекту SalesOrderHeader, а затем этот граф объектов присоединяется к контексту объекта.

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

См. также

Основные понятия

Сериализация объектов (платформа Entity Framework)
Веб-службы и модель EDM (сценарии приложений)

Другие ресурсы

Управление контекстом объекта (платформа Entity Framework)
Работа с объектами (задачи Entity Framework)