This documentation is archived and is not being maintained.

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

Visual Studio 2010

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.

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

Show: