2014-03-12 3 views
6

Linq DataContext를 응용 프로그램의 데이터베이스로 사용하고 있습니다. MVVM 패턴을 설정하고 새 레코드를 데이터베이스에 삽입 할 수 있습니다. 그러나 이러한 레코드를로드하고 업데이트하려고하면 레코드의 새 인스턴스가 백그라운드에서 만들어지고 속성 변경 내용으로 업데이트됩니다. 따라서 UI가 save 명령을 호출 할 때 원래로드 된 레코드 인스턴스는 변경되지 않고 저장되지 않습니다. 나는이 말할 수있는 것과Windows phone 8 MVVM Linq 테이블 NotifyPropertyChanging에 새 인스턴스를 만듭니다.

는로드 인스턴스 1

  • 시작 업데이트 재산
  • NotifyPropertyChanging는
  • 새로운 인스턴스 2는
  • 새로운 인스턴스 2가 업데이트로드라고
    • 이벤트

      의 순서입니다
    • 인스턴스 1에 대한 UI 변경 사항 저장 호출
    • 인스턴스 1은 아래

  • 업데이트되지 않았기 때문에 10 명
  • 어떤 변경이되지 않습니다이다 코드 내가 가진 :

    /엔티티가 */

    [Table] 
    public class User : IDisposable, INotifyPropertyChanged, INotifyPropertyChanging 
    { 
        private MyDataContext context; 
    
        public event PropertyChangedEventHandler PropertyChanged; 
        private void NotifyPropertyChanged(String propertyName) 
        { 
         PropertyChangedEventHandler handler = PropertyChanged; 
         if (null != handler) 
         { 
          handler(this, new PropertyChangedEventArgs(propertyName)); 
         } 
        } 
    
        public event PropertyChangingEventHandler PropertyChanging; 
        private void NotifyPropertyChanging(String propertyName) 
        { 
         PropertyChangingEventHandler handler = PropertyChanging; 
         if (null != handler) 
         { 
          handler(this, new PropertyChangingEventArgs(propertyName)); 
         } 
        } 
    
        public void Dispose() 
        { 
         context.Dispose(); 
        } 
    
        private Guid _id; 
        [Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "UNIQUEIDENTIFIER NOT NULL", CanBeNull = false, AutoSync = AutoSync.OnInsert)] 
        public Guid Id 
        { 
         get { return _id; } 
         set 
         { 
          if (_id != value) 
          { 
           NotifyPropertyChanging("Id"); 
           _id = value; 
           NotifyPropertyChanged("Id"); 
          } 
         } 
        } 
    
        private string _name; 
        [Column(CanBeNull = false)] 
        public string Name 
        { 
         get { return _name; } 
         set 
         { 
          if (_name != value) 
          { 
           NotifyPropertyChanging("Name"); // This line creates the new entity 
           _name = value; 
           NotifyPropertyChanged("Name"); 
          } 
         } 
        } 
    
        public User() 
        { 
         this.context = MyDataContext.GetContext(); 
        } 
    
        public override void SaveChanges() 
        { 
         if (_id == Guid.Empty) 
         { 
          this.Id = Guid.NewGuid(); 
          context.Users.InsertOnSubmit(this); 
          context.SubmitChanges(); 
         } 
         else 
         { 
          context.SubmitChanges(); 
         } 
        } 
    
        public static User NewInstance() 
        { 
         return new User 
         { 
          Name = String.Empty 
         }; 
        } 
    } 
    

    /* 이것은이 (가)입니다 *이됩니다 데이터 컨텍스트 */

    public class MyDataContext : DataContext 
    { 
        // Specify the connection string as a static, used in main page and app.xaml. 
        public static string ConnectionString = "Data Source=isostore:/MyApp.sdf;Password=pwd"; 
    
        public MyDataContext(string connectionString) : base(connectionString) { } 
    
        public static MyDataContext GetContext() 
        { 
         var context = new MyDataContext(ConnectionString); 
         return context; 
        } 
    
        public Table<User> Users; 
    } 
    

    /* 이것은보기 모델 */

    public sealed class UserViewModel : INotifyPropertyChanged 
    { 
        public event PropertyChangedEventHandler PropertyChanged; 
        protected void NotifyPropertyChanged(String propertyName) 
        { 
         PropertyChangedEventHandler handler = PropertyChanged; 
         if (handler != null) 
         { 
          handler(this, new PropertyChangedEventArgs(propertyName)); 
         } 
        } 
    
        private User _user; 
    
        public UserViewModel(Guid id) 
        { 
         using (MyDataContext context = new MyDataContext(MyDataContext.ConnectionString)) 
         { 
          _User = context.User.First(u => u.Id == id); 
         } 
        } 
    
        public UserViewModel(User user) 
        { 
         _user = user; 
        } 
    
        public UserViewModel() 
        { 
         _user = User.NewInstance(); 
        } 
    
        public string Name 
        { 
         get { return _user.Name; } 
         set 
         { 
          _user.Name = value; 
          NotifyPropertyChanged("Name"); 
         } 
        } 
    
        private ICommand _saveCommand; 
        public ICommand SaveCommand 
        { 
         get 
         { 
          return _saveCommand ?? (_saveCommand = new GenericCommand(() => 
          { 
           _user.SaveChanges(); 
          }, true)); 
         } 
        } 
    } 
    
  • +0

    이 세 부분을 하나로 묶어 놓은 코드는 보이지 않습니다. 뷰 모델은 잠재적으로 새 사용자를 만듭니다. 어떻게/어디에서 VM을 초기화하고 저장합니까? –

    답변

    2

    MyDataContext에서 나는 아래에 기본 싱글 톤 개념을 원한다고 생각합니다. 그래서 당신은 동일한 객체에 대해 작업하고 있으며 따라서 동일한 객체를 변경 사항으로 저장합니다.

    private static DataContext context = null; 
    
    public static MyDataContext GetContext() 
    { 
        if(context == null) 
         context = new MyDataContext(ConnectionString); 
        return context; 
    } 
    

    편집 - 이것은 큰 그림에서 응용 프로그램에 큰 영향을 줄 수 있습니다. 새 것을 만들 때 다시 설계해야하고 특별히 null로 설정해야하는 경우에 다시 설계해야 할 수도 있습니다.

    +0

    안녕하세요, 응답 주셔서 감사합니다, 이건 내 문제를 해결하지 못했습니다. 이 아이디어를 사용했지만 ViewModel 자체의 datacontext에 멤버 변수를 추가해야했습니다. datacontext의 notifyPropertyChanging 이벤트 처리기가 잘못된 작업을 수행 한 것처럼 보이며 처음 호출 된 경우 엔티티의 새 인스턴스를 만들려고합니다. – Koenyn