none
EF 4.1 SaveChanges() not updating RRS feed

  • Question

  • Here is is my "SaveITem() Code:

    var d = _context.MyEntities
                      .SingleOrDefault(p => p.ID == myID);
    d.Note = "test";
    _context.MyEntities.ApplyCurrentValues(d);
                _context.ObjectStateManager.ChangeObjectState(d, EntityState.Modified);
                _context.AcceptAllChanges();
                _context.SaveChanges();
    

    In DEBUG: before calling

       _context.SaveChanges();

    I have my entity in the context, it's Notes value is "test", EntityState is Modified, but... 

    after SaveChanges() is called it doesn't update anything on the DB. No exceptions... 

    Obviously, I am missing something, but I am not sure what and where... 

    Thursday, March 22, 2012 5:51 PM

Answers

  • Hi AlexeiF;

    Please read the comments below:

    var d = _context.MyEntities.SingleOrDefault(p => p.ID == myID);
    d.Notes = "Test";
    
    // This is not needed because you are working with an entity that is attached to the 
    // ObjectContext and is being tracked.
    //_context.MyEntities.ApplyCurrentValues(d);
    
    // This is not needed because once you modify an entity that is being tracked it will 
    // be mark as modified in the state manager automatically
    //_context.ObjectStateManager.ChangeObjectState(d, EntityState.Modified);
    
    // From the documentation: AcceptAllChanges will "Accepts the changes on all associated 
    // entries in the ObjectStateManager so their resultant state is either unchanged 
    // or detached., so after there is nothing to save.
    //_context.AcceptAllChanges();
    
    // EF will accept all changes after save when executed like this.
    _context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

    The above should work for you.

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mr. Javaman II Thursday, March 22, 2012 8:31 PM
    • Marked as answer by AlexeiF Thursday, March 22, 2012 8:44 PM
    Thursday, March 22, 2012 8:27 PM