2012-01-12 67 views
0

我有以下編輯方法:錯誤嘗試使用實體框架來更新實體時,4

[HttpPost] 
public ActionResult Edit(Movie movie) 
{ 
    try 
    { 
     _db.ApplyCurrentValues("Movies1",movie); 
     _db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View(); 
    } 
} 

我得到當我運行它下面的錯誤:

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.

幾個要點:

  • 我在第一次做更新時沒有收到錯誤,只有後續更新。
  • Movies1是查看edmx設計器時EntitySet的名稱。這是什麼它應該是或應該是表(電影)的名稱?
  • 我已經看到關於附件的事情,但我很困惑,究竟是什麼。

回答

2

爲了應用當前值,具有該給定密鑰的實體應存在於ObjectStateManager中。用於ApplyCurrentValues狀態的文檔

副本從所提供的對象的標量的值到具有相同的密鑰的ObjectContext在 的對象。

您可以附加實體並應用當前值。

_db.Movies.Attach(movie); 
    _db.ObjectStateManager.ChangeState(movie, EntityState.Modified); 
    _db.SaveChanges(); 
+0

我認爲從數據庫重新加載而不是調用「附加」將是一個更好的例子。你的代碼片段刪除了這個異常,但不知何故是一個空操作,因爲你正在用它自己更新一個實體=沒有改變的屬性=沒有對數據庫進行更新。 – Slauma 2012-01-13 00:43:02

+0

@Slauma是的。感謝您注意這個問題。更新答案以更改對象的狀態。 – Eranga 2012-01-13 00:50:40