我的形式包括客戶端實體屬性的子集,我還包括保存在客戶端的ID的隱藏字段。客戶端實體本身通過GET Edit操作提供。實體更新後編輯行動
現在我想做的實體更新,但到目前爲止,我只試圖不先加載從DB的實體。因爲進入POST編輯的客戶端對象具有它需要的一切。我只想更新數據存儲中實體的那些屬性。
我移植從3.5我的應用程序4.0 RC1和我的代碼看起來像現在這樣:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Client client)
{
try
{
using (DocInvoiceEntities edmx = new DocInvoiceEntities())
{
if (string.IsNullOrEmpty(client.client_firstname))
ViewData.ModelState.AddModelError("client_firstname", "Firstname!");
if (string.IsNullOrEmpty(client.client_lastname))
ViewData.ModelState.AddModelError("client_lastname", "Lastname!");
// postcode
client.PostCode = (from p in edmx.PostCodes where p.postcode.Equals(client.PostCode.postcode) select p).First();
// check for errors
if (!ViewData.ModelState.IsValid)
throw new InvalidOperationException();
// save changes to datastore
edmx.Clients.Attach(edmx.Clients.Single(c => c.client_id == client.client_id));
edmx.Clients.ApplyCurrentValues(client);
edmx.SaveChanges();
}
return RedirectToAction("Create", "Invoice");
}
catch
{
return View();
}
ApplyCurrentValues()調用拋出此異常: 「在ObjectContext中現有的對象是在加只有當現有對象處於未更改或修改狀態時,才能應用更改。「
你不覺得你會發布你使用的代碼和那些「各種例外情況」嗎? – jfar 2010-03-14 23:06:26
同意@jfar。另外:爲什麼直接綁定到實體,而不是使用編輯模型?爲什麼要「優化」一個更新,而這個更新很少是開始時的性能瓶頸? – 2010-03-15 12:57:36
「編輯模式」是什麼意思? – mare 2010-03-15 14:25:19