MVVM Light:使用DataService检索数据库项

时间:2013-09-27 21:12:51

标签: c# wpf entity-framework mvvm-light

我正在研究MVVM Light示例项目并正在实现SimpleIoc ViewModelLocator。我已经能够构建一个IRepositoryService,它从数据库(即公司,员工等)中检索信息,并将信息存储到ObservableCollection中。然后,IRepositoryService将ObservableCollection返回给ViewModel。以下是如何实现的:

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);
        }

    }
}

然后在ViewModel中使用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 个答案:

答案 0 :(得分:0)

以下是我的一个视图模型的示例

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();
    }
}