是的,這是可能的,但你必須按正確的順序。最簡單的方法是:
var order1 = new Order { Id = 1 };
context.Orders.Attach(order1); // Now context knows the order and it tracks it as unchanged
var customer = new Customer();
context.Customers.AddObject(customer); // Now context knows the customer and it tracks it as a new
customer.Orders.Add(order1); // Now context knows about new relation between new customer and existing order
如果你這樣做,你在你的例子顯示,你會撥打:
context.Customers.AddObject(customer);
和上下文將跟蹤客戶和所有相關的訂單作爲一個新的,所以你將有手動將所有訂單狀態更改爲不變以避免重複插入:
foreach (var order in customer.Orders)
{
if (order.Id != 0)
{
context.ObjectStateManager.ChangeObjectState(order, EntityState.Unchagned);
}
}