Daily Archives: October 13, 2017

Move object between EditingContexts

I have created an EnterpriseObject and have registered it on the default EditingContext.

MyObject my = MyObject.createMyObject(session.defaultEditingContext(), "Foo");
session.defaultEditingContext().saveChanges();

Now, the object is related to this EditingContext. If I create another EOEditingContext and try to use the MyObject instance there as part of a relation, it will go wrong.

EOEditingContext ec = new EOEditingContext();
AnotherObject xyz = AnotherObject.createAnotherObject(ec, my, "Bar");
ec.saveChanges();

This produces an exception:

Cannot obtain globalId for an object which is registered in an other than the databaseContext's active editingContext

The problem is, that the instance of MyObject is not known within the second EOEditingContext. To correct that, the MyObject class has a method localInstanceIn(), which you can call:

EOEditingContext ec = new EOEditingContext();
my.localInstanceIn(ec);
AnotherObject xyz = AnotherObject.createAnotherObject(ec, my, "Bar");
ec.saveChanges();