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

В данном разделе показывается, как можно использовать объект EntityReference для изменения связи между двумя объектами в контексте объекта. При вызове метода SaveChanges изменение в связи сохраняется в базе данных как изменение во внешнем ключе в связанной таблице. Дополнительные сведения см. в разделе Как обеспечить выполнение бизнес-логики при изменении ассоциаций.

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

Пример

В данном примере показывается, как можно использовать объект EntityReference для изменения связи между объектом SalesOrderHeader и связанным объектом Address, представляющим адрес доставки для заказа.

' Define the order and new address IDs. 
Dim orderId As Integer = 43669
Dim addressId As Integer = 26

Using context As New AdventureWorksEntities()
    ' Get the billing address to change to. 
    Dim address As Address = context.Addresses.Single(Function(c) c.AddressID = addressId)

    ' Get the order being changed. 
    Dim order As SalesOrderHeader = context.SalesOrderHeaders.Single(Function(o) o.SalesOrderID = orderId)

    ' You do not have to call the Load method to load the addresses for the order, 
    ' because lazy loading is set to true 
    ' by the constructor of the AdventureWorksEntities object. 
    ' With lazy loading set to true the related objects are loaded when 
    ' you access the navigation property. In this case Address. 

    ' Write the current billing street address. 
    Console.WriteLine("Current street: " & order.Address.AddressLine1)

    ' Change the billing address. 
    If Not order.Address.Equals(address) Then
        ' Use Address navigation property to change the association. 
        order.Address = address

        ' Write the changed billing street address. 
        Console.WriteLine("Changed street: " & order.Address.AddressLine1)
    End If

    ' If the address change succeeds, save the changes. 
    context.SaveChanges()

    ' Write the current billing street address. 
    Console.WriteLine("Current street: " & order.Address.AddressLine1)
End Using
// Define the order and new address IDs.
int orderId = 43669;
int addressId = 26;

using (AdventureWorksEntities context
    = new AdventureWorksEntities())
{
    // Get the billing address to change to.
    Address address =
        context.Addresses.Single(c => c.AddressID == addressId);

    // Get the order being changed.
    SalesOrderHeader order =
        context.SalesOrderHeaders.Single(o => o.SalesOrderID == orderId);

    // You do not have to call the Load method to load the addresses for the order,
    // because  lazy loading is set to true 
    // by the constructor of the AdventureWorksEntities object. 
    // With  lazy loading set to true the related objects are loaded when
    // you access the navigation property. In this case Address.

    // Write the current billing street address.
    Console.WriteLine("Current street: "
        + order.Address.AddressLine1);

    // Change the billing address.
    if (!order.Address.Equals(address))
    {
        // Use Address navigation property to change the association.
        order.Address = address;

        // Write the changed billing street address.
        Console.WriteLine("Changed street: "
            + order.Address.AddressLine1);
    }

    // If the address change succeeds, save the changes.
    context.SaveChanges();

    // Write the current billing street address.
    Console.WriteLine("Current street: "
        + order.Address.AddressLine1);
}

См. также

Задачи

Как использовать свойство внешнего ключа для изменения связей между объектами
Как обеспечить выполнение бизнес-логики при изменении ассоциаций

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

Работа с объектами (платформа Entity Framework)
Определение отношений и управление отношениями (платформа Entity Framework)