0

Somewhere, I have

Order o = db.Orders.First(o => o.ID == 6);
...
o.Details.Add(new OrderDetail(1,2));

and in button click event

...
Order o1 = db.Orders.FirstOrDefault(o2=>o2.ID == o.ID);
o1.Details.Clear();
foreach(OrderDetail od in o.Details){
o.Details.Add(od);
}
db.SaveChange();
...

I meet this error:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll

Additional information: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

It's seem like I cannot modify the object which created by another DbContext or by hand, is there a workround way?

Andiana
  • 1,912
  • 5
  • 37
  • 73
  • In short, you can not use objects from different contexts - have a look here - http://stackoverflow.com/questions/15274539/the-relationship-between-the-two-objects-cannot-be-defined-because-they-are-atta – fly_ua Mar 20 '15 at 14:29
  • You need to attach the object to the new DbContext first, you can use the Attach() method here https://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach%28v=vs.110%29.aspx – Jon Mar 20 '15 at 15:16

0 Answers0