这一直困扰我一段时间,我希望能够做的是通过更改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()
方法,但我发现使用新值更新数据库非常困难。
我们非常感谢任何建议。
答案 0 :(得分:0)
看起来问题可能出在您的EF图层中。您是否有任何单元测试来检查新员工记录的创建是否正常?你能闯入CreateEmployee并检查Emp.ID字段吗?看看它是否设置了什么。如果是,则新记录的创建正常工作。一个观察结果,如果可以的话:您的数据访问服务不需要返回ObservableCollection。我假设你的视图模型类中已经有一个可观察的集合。如果要保持视图中数据网格与视图模型类中的observable collection属性之间的绑定,则不应重新分配视图模型类的OC属性。你应该遵循的模式是:
您可以保留来自GetEmployees的OC返回,但是在您的视图模型中,您仍然需要将所有项目逐个传输到最有可能绑定到视图中的数据网格的属性中。如果只是将GetEmployees()返回的OC列表分配给视图模型的属性,那么绑定将会消失。
也许你的数据网格没有正确刷新,这就是为什么你得出的结论是数据库实际上并没有更新。
HTH, 埃迪