2011-10-03 51 views
0

我有客戶訂單集合。我有一些訂單identificators我需要添加到新的客戶實例是這樣的:加入收藏現有辨識器

var customer = new Customer(); 
customer.Orders.Add(new Order() { Id = 1 }); 
customer.Orders.Add(new Order() { Id = 2 }); 
customer.Orders.Add(new Order() { Id = 3 }); 

是否有可能不retrieveing approapriate單實例?

回答

2

是的,這是可能的,但你必須按正確的順序。最簡單的方法是:

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