' Specify the order to which to add the item.
Dim orderId = 43680
' Create the key that represents the order.
Dim orderKey As EntityKey = _
New EntityKey("AdventureWorksEntities.SalesOrderHeader", _
"SalesOrderID", orderId)
' Create an order that we can attach.
Dim order As New SalesOrderHeader()
order.EntityKey = orderKey
' Ensure that the ID property matches the key.
order.SalesOrderID = CType(orderKey.EntityKeyValues(0).Value, Integer)
Using context As AdventureWorksEntities = _
New AdventureWorksEntities()
Try
' Attach the newly created object.
context.Attach(order)
' Create a new item using the static Create method
' and add it to the attached order.
order.SalesOrderDetail.Add( _
SalesOrderDetail.CreateSalesOrderDetail(0, _
0, 2, 750, 1, Convert.ToDecimal(2171.2942), 0, 0, _
Guid.NewGuid(), DateTime.Today))
context.SaveChanges()
Catch ex As InvalidOperationException
Console.WriteLine(String.Format("Ensure that the key value '{0}' " _
& "matches the value of the '{1}' property.", _
order.EntityKey.EntityKeyValues(0).Value, _
order.EntityKey.EntityKeyValues(0).Key))
Catch ex As UpdateException
Console.WriteLine(String.Format("An error has occured. Ensure that " _
& "an object with an value of '{0}' for key property '{1}' exists.", _
order.EntityKey.EntityKeyValues(0).Value, _
order.EntityKey.EntityKeyValues(0).Key))
End Try
End Using