entity-frameworkentityobjectcontext

How do I get the old values of an entity?


How do I get the old values of an entity?

follows the example..

public void Update(User user)
    ValidateEntity(user, OperationType.Update);

    oldUser = (how do I get the old values ​​(database) of the entity User?)

    Set.Attach(user);
    Context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
    Context.SaveChanges();

    OnUpdated(user, oldUser);
}

Solution

  • Try this:

    public void Update(User user)
        ValidateEntity(user, OperationType.Update);
    
        var oldUser = Set.Single(u => u.Id == user.Id);
        Context.Detach(oldUser);
    
        Set.Attach(user);
        Context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
        Context.SaveChanges();
    
        OnUpdated(user, oldUser);
    }
    

    Or this:

    public void Update(User user) 
    {
        ValidateEntity(user, OperationType.Update);
    
        var oldUser = Set.Single(u => u.Id == user.Id);
        Set.ApplyCurrentValues(user);
        Context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
    
        OnUpdated(user, Context.ObjectStateManager.GetOjectStateEntry(user).OriginalValues);
    
        Context.AcceptAllChanges(); 
    }