Using Automapper to update an existing Entity POCO

陌路散爱 提交于 2019-11-28 06:55:20

If you use Automapper like that, it returns a new Patient object and the references to the enity framework graph are not kept. You have to use it like this:

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

There seem to be two approaches to dealing with the EF proxy issue:

  1. Switch off ObjectContext.ContextOptions.ProxyCreationEnabled, either for the whole application (in EF Context constructor or EDMX), or for the query where you need to guarantee getting an actual Entity object rather than a proxy.
  2. Using an extension to Automapper, documented here: https://gist.github.com/935461.

Note. The latter is commented with "Room for improvement. See: Automapper : mapping issue with inheritance and abstract base class on collections with Entity Framework 4 Proxy Pocos".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!