2013-09-27 43 views
2

我正在研究示例MVVM Light項目並實施SimpleIoc ViewModelLocator。我已經能夠構建一個從數據庫(即公司,員工等)檢索信息的IRepositoryService,並將信息存儲到ObservableCollection中。 IRepositoryService然後將ObservableCollection返回給ViewModel。下面是這是如何實現的:MVVM Light:使用DataService檢索數據庫項目

public interface IRepositoryService 
{ 

    void GetCompanies(Action<ObservableCollection<Company>, Exception> callback); 

    void GetEmployees(Action<ObservableCollection<Employee>, Exception> callback); 

} 


class RepositoryService : IRepositoryService 
{ 
    public void GetCompanies(Action<ObservableCollection<Company>, Exception> callback) 
    { 
     using (var context = new SidekickEntities()) 
     { 
      var _companies = from co in context.Companies 
          select co; 
      callback(new ObservableCollection<Company>(_companies), null); 
     } 
    } 

    public void GetEmployees(Action<ObservableCollection<Employee>, Exception> callback) 
    { 
     using (var context = new SidekickEntities()) 
     { 
      var _employees = from co in context.Employees 
          select co; 
      callback(new ObservableCollection<Employee>(_employees), null); 
     } 

    } 
} 

的RepositoryService然後在視圖模型作爲這樣的:

public sealed class CompanyViewModel : ViewModelBase //, IPageViewModel 
    { 
     private readonly IRepositoryService _dataService; 
     private ObservableCollection<Company> _companyList; 

     /// <summary> 
     /// Initializes a new instance of the CompanyViewModel class. 
     /// </summary> 
     public CompanyViewModel(IRepositoryService dataService) 
     { 

      Console.WriteLine("CompanyViewModel DataService Constructor"); 
      try 
      { 
       _dataService = dataService; 
       CompanyList = new ObservableCollection<Company>(); 
       _dataService.GetCompanies(
        (companies, error) => 
        { 
         if (error != null) 
         { 
          return; 
         } 
         CompanyList = companies; 
        } 
       ); 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 

     } 


     public ObservableCollection<Company> CompanyList 
     { 
      get 
      { 
       return _companyList; 
      } 
      set 
      { 
       if (_companyList == value) 
       { 
        return; 
       } 

       _companyList = value; 
       RaisePropertyChanged(CompanyListPropertyName); 
      } 

     } 

    } 

這一切的偉大工程,使我在DataGrid中顯示的數據,但我會想知道用於將更改保存回數據庫的方法是什麼?例如,如果我在CompanyViewModelConstructor()的末尾添加了以下內容,我將如何將新列表保存回數據庫?我正在使用Entity Framework 5.x來訪問數據庫。

CompanyList.Add(new Company(-1, "Chipotle", "1400 High Street", "", "Columbus", "OH", "43235")); 
+1

只需添加對象(S)到您的ObservableCollection(或修改現有對象)中的一個的例子,一旦保存命令以某種方式觸發,通過ObservableCollection中的對象進行循環訪問,並根據需要進行更新或插入。很明顯,您想要將這些方法添加到IRepositoryService中,因爲您已經在使用它來獲取記錄... –

+0

我將創建一個視圖模型,其中包含用於編輯和添加的命令。這樣一切都包含在一個地方。 – 2013-09-27 22:07:39

回答

0

這裏是我的ViewModels

class YearModel : INotifyPropertyChanged 
{ 
    #region Members 

    Year _year; 

    #endregion 

    #region Properties 

    public Year Year 
    { 
     get { return _year; } 
    } 

    public Int32 id 
    { 
     get { return Year.id; } 
     set 
     { 
      Year.id = value; 
      NotifyPropertyChanged("id"); 
     } 
    } 

    public String Code 
    { 
     get { return Year.Code; } 
     set 
     { 
      Year.Code = value; 
      NotifyPropertyChanged("Code"); 
     } 
    } 

    public String Description 
    { 
     get { return Year.Description; } 
     set 
     { 
      Year.Description = value; 
      NotifyPropertyChanged("Description"); 
     } 
    } 

    public DateTime DateCreated 
    { 
     get { return Year.DateCreated; } 
     set 
     { 
      Year.DateCreated = value; 
      NotifyPropertyChanged("DateCreated"); 
     } 
    } 

    public Int32 CreatedByID 
    { 
     get { return Year.CreatedByID; } 
     set 
     { 
      Year.CreatedByID = value; 
      NotifyPropertyChanged("CreatedByID"); 
     } 
    } 

    public String CreatedByDesc 
    { 
     get { return Year.CreatedByDesc; } 
     set 
     { 
      Year.CreatedByDesc = value; 
      NotifyPropertyChanged("CreatedByDesc"); 
     } 
    } 

    public DateTime DateEdited 
    { 
     get { return Year.DateEdited; } 
     set 
     { 
      Year.DateEdited = value; 
      NotifyPropertyChanged("DateEdited"); 
     } 
    } 

    public Int32 EditedByID 
    { 
     get { return Year.EditedByID; } 
     set 
     { 
      Year.EditedByID = value; 
      NotifyPropertyChanged("EditedByID"); 
     } 
    } 

    public String EditedByDesc 
    { 
     get { return Year.EditedByDesc; } 
     set 
     { 
      Year.EditedByDesc = value; 
      NotifyPropertyChanged("EditedByDesc"); 
     } 
    } 

    #endregion 

    #region Construction 

    public YearModel() 
    { 
     this._year = new Year 
     { 
      id = 0, 
      Code = "", 
      Description = "", 
      DateCreated = new DateTime(1900, 01, 01, 00, 00, 00), 
      CreatedByID = 0, 
      CreatedByDesc = "", 
      DateEdited = new DateTime(1900, 01, 01, 00, 00, 00), 
      EditedByID = 0, 
      EditedByDesc = "" 
     }; 
    } 

    #endregion 

    #region Property Change Events 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected void NotifyPropertyChanged(String info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 

    #endregion 

    #region Commands 

    public ICommand EditCommand 
    { 
     get { return new RelayCommand(EditYear); } 
    } 

    public ICommand AddCommand 
    { 
     get { return new RelayCommand(AddYear); } 
    } 

    #endregion 

    #region Functions 

    public void EditYear() 
    { 
     try 
     { 

      Service1Client service = new Service1Client(); 

      Year y = new Year(); 
      y.id = this.id; 
      y.Code = this.Code; 
      y.Description = this.Description; 
      y.DateEdited = DateTime.Now; 
      y.EditedByID = (Int32)Application.Current.Resources["UserID"]; 


      service.EditYear(y); 
      MessageBox.Show("Your Year was edited successfully", "Success", MessageBoxButton.OK); 
     } 
     catch (Exception ex) 
     { 
      logError le = new logError(); 
      le.log(ex, "YearViewModel", "EDIT"); 
     } 
    } 

    public void AddYear() 
    { 
     try 
     { 
      Service1Client service = new Service1Client(); 

      Year y = new Year(); 
      y.Code = this.Code; 
      y.Description = this.Description; 
      y.DateCreated = DateTime.Now; 
      y.CreatedByID = (Int32)Application.Current.Resources["UserID"]; 
      y.DateEdited = this.DateEdited; 


      service.AddYear(y); 
      MessageBox.Show("Your new Year was entered successfully", "Success", MessageBoxButton.OK); 
     } 
     catch (Exception ex) 
     { 
      logError le = new logError(); 
      le.log(ex, "YearViewModel", "ADD"); 
     } 
    } 

    #endregion 
} 

}

<Button Content="Save New" 
    DataContext="{StaticResource ResourceKey=NewYear}" 
    Command="{Binding Path=AddCommand}"/> 


class RelayCommand : ICommand 
{ 
    Action action; 

    public RelayCommand(Action execute) 
    { 
     action = execute; 
    } 

    public bool CanExecute(object parameter) 
    { 
     return true; 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     action(); 
    } 
}