我正在开发一个示例 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"));