EF returns old values

前端 未结 3 1995
甜味超标
甜味超标 2020-12-18 02:25

I\'m using EF6 + WPF with MVVM design pattern in my desktop application. I\'m using also Autofac as DI container.

I read a lot about EF context lifetime management

3条回答
  •  不知归路
    2020-12-18 02:45

    If you use MVVM then you can do: your view bind to your view model with property type EntityViewModel (is a wrapper for the Entity). All changes immediately appear in the EntityViewModel. If you want to undo changes - invoke method EntityViewModel.Undo(). If you want to apply the changes to the entity - invoke EntityViewModel.Apply(). Then you can invoke method DbContext.SaveChanges().

    public class Entity 
    {
        public string Id { get; set; }
        public string State { get; set; }
    }
    
    public class EntityViewModel : ViewModelBase
    {
        private string _state;
    
        public EntityViewModel(Entity entity)
        {
            Entity = entity;
            _state = entity.State;
        }
    
        public string State
        {
            get { return _state; }
            set
            {
                if (value == _state)
                    return;
                _state = value;
                base.OnPropertyChanged("State");
            }
        }
    
        public Entity Entity {get; private set; }
    
        public void ApplyChanges()
        {
            Entity.State = _state;
        }
    
        public void Undo()
        {
            State = entity.State;
        }
    }
    

    This is a good division of responsibilities, which fits into the MVVM.

提交回复
热议问题