使用DataAccessService MVVM Light更新数据库

时间:2015-08-28 13:07:08

标签: c# wpf mvvm

这一直困扰我一段时间,我希望能够做的是通过更改ObservableCollection或记录类SquirrelDataGridActiveView来更新数据库上的现有记录。
这是我的DataAccessService:

public interface IDataAccessService
{
    ObservableCollection<SquirrelDataGridActiveView> GetEmployees();
    void UpdateRecord(SquirrelDataGridActiveView Emp);
    int CreateEmployee(SquirrelDataGridActiveView Emp);
}

/// <summary>
/// Class implementing IDataAccessService interface and implementing
/// its methods by making call to the Entities using CompanyEntities object
/// </summary>
public class DataAccessService : IDataAccessService
{
    Drive_SHEntities context;
    public DataAccessService()
    {
        context = new Drive_SHEntities();
    }
    public ObservableCollection<SquirrelDataGridActiveView> GetEmployees()
    {
        ObservableCollection<SquirrelDataGridActiveView> Employees = new ObservableCollection<SquirrelDataGridActiveView>();
        foreach (var item in context.SquirrelDataGridActiveViews)
        {
            Employees.Add(item);
        }
        return Employees;
    }

    public int CreateEmployee(SquirrelDataGridActiveView Emp)
    {
        context.SquirrelDataGridActiveViews.Add(Emp);
        context.SaveChanges();
        return Emp.ID;
    }

    public void UpdateRecord(SquirrelDataGridActiveView temp)
    {

    }
}

正如您所看到的那样,已经存在GetEmployees()方法和CreateEmployee()方法,但我发现使用新值更新数据库非常困难。

我们非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

看起来问题可能出在您的EF图层中。您是否有任何单元测试来检查新员工记录的创建是否正常?你能闯入CreateEmployee并检查Emp.ID字段吗?看看它是否设置了什么。如果是,则新记录的创建正常工作。一个观察结果,如果可以的话:您的数据访问服务不需要返回ObservableCollection。我假设你的视图模型类中已经有一个可观察的集合。如果要保持视图中数据网格与视图模型类中的observable collection属性之间的绑定,则不应重新分配视图模型类的OC属性。你应该遵循的模式是:

  • 从您的数据访问服务的GetEmployees()方法返回IEnumeration;
  • 可选,但建议让GetEmployees等待;
  • 在view-model类中,清除OC属性的内容,然后逐个添加GetEmployees()方法返回的IEnumeration集合中的所有项。这样,您的绑定将继续有效,数据库中的任何更新都将反映在视图的数据网格中。

您可以保留来自GetEmployees的OC返回,但是在您的视图模型中,您仍然需要将所有项目逐个传输到最有可能绑定到视图中的数据网格的属性中。如果只是将GetEmployees()返回的OC列表分配给视图模型的属性,那么绑定将会消失。

也许你的数据网格没有正确刷新,这就是为什么你得出的结论是数据库实际上并没有更新。

HTH, 埃迪