Share via


HOW TO:使用外部索引鍵屬性變更物件間的關聯性

本主題示範如何使用外部索引鍵屬性來變更物件內容中兩個物件之間的關聯性。 如需更多範例,請參閱 使用外部索引鍵 (Entity Framework)

本主題的範例根據 Adventure Works Sales Model。若要執行此主題中的程式碼,您必須已經將 Adventure Works Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)HOW TO:手動設定 Entity Framework 專案HOW TO:手動設定 Entity Framework 專案

範例

本範例將示範如何使用外部索引鍵屬性來變更 SalesOrderHeader 物件與代表訂單帳單地址之相關 Address 物件間的關聯性。

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

}

另請參閱

工作

HOW TO:使用 EntityReference 變更物件間的關聯性 (Entity Framework)

概念

定義及管理關聯性