使用Automapper更新现有的实体POCO

时间:2012-11-09 19:29:38

标签: asp.net-mvc entity-framework-4 viewmodel automapper dbcontext

我正在使用EF4 DbContext为ASP.NET MVC应用程序提供模型。我使用ViewModels为视图和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而不是代理?
  2. 这是执行更新的最佳做法吗?

2 个答案:

答案 0 :(得分:42)

如果你像这样使用Automapper,它会返回一个新的Patient对象,并且不会保留对enity框架图的引用。你必须像这样使用它:

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

答案 1 :(得分:1)

处理EF代理问题似乎有两种方法:

  1. 为整个应用程序(在EF上下文构造函数或EDMX中)关闭ObjectContext.ContextOptions.ProxyCreationEnabled,或者在需要保证获取实际实体对象而不是代理的查询时关闭{{1}}。
  2. 使用Automapper的扩展程序,在此处记录:https://gist.github.com/935461
  3. 请注意。后者的评论是“改进空间。见:Automapper : mapping issue with inheritance and abstract base class on collections with Entity Framework 4 Proxy Pocos”。