views:

15

answers:

1

Hello,

I am using an ObservableCollection to wrap some of my generated entity framework objects. When the user wants to edit some values , i am opening a popup windows that contains fields, and when the user changes and press save - the changes are saved to the database, and the binded controls are changes as it is an observablecollection.

To prevent the user from working on the same binded object (it causes the visual change of every binded control on the same time) i want to use some functionality the clone the object, and then detach the original, attach the cloned object, and save it to the database. The problem is that the cloned object does not save properly to the database. If i try only to detach the object, edit and then attach - when detached it loses all its parent and child refernces...

What is the CRUD standard in WPF? How can i cleanly edit a current row, while keeping it in an ObservableCollection?

Please Help....

Oran

+1  A: 

Well it seems that i have found a fine solution.

  1. First implement your cloneable object container :

    public class ClonableObjectContainer : Object , ICloneable
    {
        private Object data;
    
    
    
    public ClonableObjectContainer(Object obj)
    {
        data = obj;
    }
    
    
    public Object Data
    {
        get { return data; }
    }
    
    
    public object Clone()
    {
        return (ClonableObjectContainer)this.MemberwiseClone();
    }
    
    }
  2. Then use this object with its Clone method to create your detached edit object:

             ClonableObjectContainer coc = new ClonableObjectContainer(actor);
             EntityObject editEntity = (EntityObject)coc.Data;
    
  3. After performing changes, detach the original object from the ObjectContext , attach the cloned object, change its state to EntityState.Modified and gracefully save:

            ContextManager.CurrentObjectContext.Detach(oldItem);
            ContextManager.CurrentObjectContext.Attach((IEntityWithKey)item);
            ContextManager.CurrentObjectContext.ObjectStateManager.ChangeObjectState(item, EntityState.Modified); 
            ContextManager.Save();
    

Hope it helps... Oran

EDIT : If the followings does not work for you, please check the continued discussion : http://stackoverflow.com/questions/4034477/entity-framework-attach-exception-after-clone

OrPaz