Asp.net-Mvc

使用 Automapper 更新現有實體 POCO

  • November 9, 2012

我正在使用 EF4 DbContext 為 ASP.NET MVC 應用程序提供模型。我使用 ViewModel 向視圖提供數據,並使用 Automapper 來執行 EF POCO 和 ViewModel 之間的映射。Automapper 做得很好,但我不清楚在 ViewModel 被發送回控制器以執行更新後使用它的最佳方式。

我的想法是使用 ViewModel 中包含的鍵獲取 POCO 對象。然後我想使用 Automapper 使用 ViewModel 中的數據更新 POCO:

[HttpPost]
public ActionResult Edit(PatientView viewModel)
{
   Patient patient = db.Patients.Find(viewModel.Id); 
   patient = Mapper.Map<ViewModel, Patient>(viewModel, patient);
   ...
   db.SaveChanges();
   return RedirectToAction("Index");
}

兩個問題:

  1. Find() 方法返回一個代理而不是一個導致 Automapper 抱怨的 POCO。如何獲取 POCO 而不是 Proxy?
  2. 這是執行更新的最佳做法嗎?

如果您像這樣使用 A​​utomapper,它會返回一個新的 Patient 對象,並且不會保留對實體框架圖的引用。你必須像這樣使用它:

[HttpPost]
public ActionResult Edit(PatientView viewModel)
{
   Patient patient = db.Patients.Find(viewModel.Id); 
   Mapper.Map(viewModel, patient);
   ...
   db.SaveChanges();
   return RedirectToAction("Index");
}

引用自:https://stackoverflow.com/questions/13314666