我正在使用 EF4 DbContext 为 ASP.NET MVC 应用程序提供模型。我使用 ViewModel 向 View 提供数据,并使用 Automapper 执行 EF POCO 和 ViewModel 之间的映射。 Automapper 做得很好,但我不清楚在 ViewModel 被发送回 Controller 以执行更新后使用它的最佳方式。
我的想法是使用 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");
}
两个问题:
最佳答案
如果您像这样使用 Automapper,它会返回一个新的 Patient 对象,并且不会保留对 Entity Framework 图的引用。你必须像这样使用它:
[HttpPost]
public ActionResult Edit(PatientView viewModel)
{
Patient patient = db.Patients.Find(viewModel.Id);
Mapper.Map(viewModel, patient);
...
db.SaveChanges();
return RedirectToAction("Index");
}
关于asp.net-mvc - 使用 Automapper 更新现有实体 POCO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13314666/