如何在需要插入时在L2E或EF中使用外键?

时间:2010-04-13 20:01:50

标签: c# linq linq-to-entities

我知道在检索过程中,我可以使用Include()来加载相关的实体(how to use Foreign key in L2E or EF?)。但是当我想保存或插入数据时,如何处理那些引用实体?

1 个答案:

答案 0 :(得分:1)

您需要将对象挂在其图表中,然后调用保存更改。 ObjectContext负责其余部分。

Customer customer = myObjectContext.Single(c => c.Name == "Bob");

//new up an Order instance that has never been in the database.
Order order = GetOrderForCar();

//Add order to the Orders ObjectSet of a Customer
// This connects order to our ObjectContext.
customer.Orders.Add(order);

myObjectContext.SaveChanges();