How to: Use the Foreign Key Property to Change Relationships Between Objects

This topic shows how to use the foreign key property to change a relationship between two objects in the object context. For more examples, see Working with Foreign Keys.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the Adventure Works Sales Model to your project and configured your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework) or How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

This example shows how to use the foreign key property to change a relationship between a SalesOrderHeader object and a related Address object that represents the billing address for the order.

Dim orderId As Integer = 43669
Dim addressId As Integer = 24

Using context As New AdventureWorksEntities()
    ' Get the order being changed. 
    Dim order As SalesOrderHeader = context.SalesOrderHeaders.First(Function(o) o.SalesOrderID = orderId)

    ' Chage the billing address. 
    order.BillToAddressID = addressId

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

    ' Save the changes. 

    context.SaveChanges()
End Using
int orderId = 43669;
int addressId = 24;

using (AdventureWorksEntities context
    = new AdventureWorksEntities())
{
    // Get the order being changed.
    SalesOrderHeader order = context.SalesOrderHeaders.First(o => o.SalesOrderID == orderId);

    // Chage the billing address.
    order.BillToAddressID = addressId;

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

    // Save the changes.
    context.SaveChanges();

}

See Also

Tasks

How to: Use an EntityReference to Change Relationships Between Objects

Concepts

Defining and Managing Relationships