2012-08-14 166 views
2

控制器實體框架更新實體?

[HttpPost] 
public ActionResult EditUserProfile(UserProfiles _postedUserProfile) 
{ 
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single(); 
    orjinalUserProfile.AboutMe = _postedUserProfile.AboutMe; 
    orjinalUserProfile.Birthday = _postedUserProfile.Birthday; 
    orjinalUserProfile.Comments = _postedUserProfile.Comments; 
    ...... // there are lines more 
    entity.SaveChanges(); 
    return View(); 
} 

我更新的實體像上面。但我認爲這種方式並不好。是否有任何解決方案在一行中更新實體,例如插入操作如entity.AddToUserProfiles

謝謝。

回答

0

您可以使用ApplyCurrentValues方法。

下面是一個例子:ApplyCurrentValues in EF 4

基本上是:

[HttpPost] 
public ActionResult EditUserProfile(UserProfiles _postedUserProfile) 
{ 
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single(); 
    entity.UserProfiles.ApplyCurrentValues(_postedUserProfile); 
    entity.SaveChanges(); 
    return View(); 
} 
+0

我試試這個。但數據庫沒有改變。我不明白上面的代碼中他們之間的orjinal和修飾實體如何匹配? – 2012-08-14 23:54:51

+0

我注意到我原來的帖子有錯誤。我正在將orjinalUserProfile傳遞給ApplyCurrentValues方法,而不是_postedUserProfile。我編輯過來反映這個變化。請嘗試使用此對象。 – echo 2012-08-16 02:45:23

+0

它仍然不起作用。我們是否應該確保orjinal和已發佈實體之間的關係? – 2012-08-16 21:54:03