asp.net-mvc – 使用Automapper更新现有的实体POCO

我使用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");
}

两个问题:

> Find()方法返回一个代理而不是一个导致Automapper投诉的POCO.我如何获得POCO而不是代理?
>这是执行更新的最佳做法吗?

解决方法

如果您使用这样的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");
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...