Search code examples
eclipseeclipse-emfeclipse-emf-ecore

Emf Write transaction


I have the resource file in the explorer if i try to modify that resource file through transaction editing domain I am getting exception as

java.lang.IllegalStateException: Cannot modify resource set without a write transaction at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.assertWriting(TransactionChangeRecorder.java:348) at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.appendNotification(TransactionChangeRecorder.java:302) at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.processObjectNotification(TransactionChangeRecorder.java:284) at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.notifyChanged(TransactionChangeRecorder.java:240) at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) at org.eclipse.emf.common.notify.impl.NotificationImpl.dispatch(NotificationImpl.java:1027) at org.eclipse.emf.common.notify.impl.NotifyingListImpl.addUnique(NotifyingListImpl.java:299) at org.eclipse.emf.common.util.AbstractEList.add(AbstractEList.java:303)


Solution

  • I believe the problem is, that you're trying to execute a write transaction within another write transaction. A command should do the trick. This can be done using the EditingDomainof your Model: (Make sure org.eclipse.emf.transaction is in your dependencies)

    import org.eclipse.emf.transaction.TransactionalEditingDomain; 
    import org.eclipse.emf.transaction.util.TransactionUtil;
    
    public void doEditing(EObject element) {
        // Make sure your element is attached to a resource, otherwise this will return null
        TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(element);
        domain.getCommandStack().execute(new RecordingCommand(domain) {
    
            @Override
            protected void doExecute() {
                // Implement your write operations here,
                // for example: set a new name
                element.eSet(element.eClass().getEStructuralFeature("name"), "aNewName");
            }
        });
    }