本主题演示如何使用外键属性在对象上下文中更改两个对象间的关系。 有关更多示例,请参见使用外键(实体框架)。
本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,则必须已经将 Adventure Works 销售模型添加到了您的项目中,并且已经将项目配置为使用实体框架。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)或如何:手动配置实体框架项目和如何:手动定义实体数据模型(实体框架)。
示例
此示例演示如何使用外键属性更改 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();
}
另请参见
任务
如何:使用 EntityReference 更改对象之间的关系(实体框架)