Niv*_*kia 1 c# entity-framework-4
尝试更新数据库时,此代码出错
错误:在ObjectStateManager中找不到具有与提供的对象的键匹配的键的对象.验证提供的对象的键值是否与必须应用更改的对象的键值匹配.
public void UpdateAccuralSettings(SystemTolerance updatedObject)
{
_source.SystemTolerances.ApplyCurrentValues(updatedObject);
_source.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
ApplyCurrentValues 仅当实体首次从数据库加载时才起作用(如果你没有使用你用来加载它的相同上下文,那么很可能不是这样):
public void UpdateAccuralSettings(SystemTolerance updatedObject)
{
_source.SystemTolerances.Single(x => x.Id == updatedObject.Id);
_source.SystemTolerances.ApplyCurrentValues(updatedObject);
_source.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
如果您只想保存当前数据而不重新加载实体使用:
public void UpdateAccuralSettings(SystemTolerance updatedObject)
{
_source.SystemTolerances.Attach(updatedObject);
_source.ObjectStateManager.ChangeEntityState(updatedObject, EntityState.Modified);
_source.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)