添加到集合现有识别器

时间:2011-10-03 08:40:05

标签: .net entity-framework

我有订单收集的客户。我有一些订单标识符,我需要添加到新的Customer实例中,如下所示:

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

是否可以在不检索合适的订单实例的情况下进行?

1 个答案:

答案 0 :(得分: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);
   }
}