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"));
只需添加對象(S)到您的ObservableCollection(或修改現有對象)中的一個的例子,一旦保存命令以某種方式觸發,通過ObservableCollection中的對象進行循環訪問,並根據需要進行更新或插入。很明顯,您想要將這些方法添加到IRepositoryService中,因爲您已經在使用它來獲取記錄... –
我將創建一個視圖模型,其中包含用於編輯和添加的命令。這樣一切都包含在一個地方。 – 2013-09-27 22:07:39