使用Automapper更新现有的实体POCO [英] Using Automapper to update an existing Entity POCO

查看:190
本文介绍了使用Automapper更新现有的实体POCO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF4的DbContext提供一个ASP.NET MVC应用程序模型。我用的ViewModels提供数据的意见和Automapper执行EF波苏斯和的ViewModels之间的映射。 Automapper做了伟大的工作,但我不清楚的最好的方式来使用它的视图模型后贴回控制器来进行更新。

我的想法是使用包含在视图模型一键搞定POCO对象。然后,我想用Automapper从视图模型数据更新POCO:

  [HttpPost]
公众的ActionResult编辑(PatientView视图模型)
{
    病人病人= db.Patients.Find(viewModel.Id)​​;
    病人= Mapper.Map<视图模型,病人GT;(视图模型,病人);
    ...
    db.SaveChanges();
    返回RedirectToAction(「指数」);
}

两个问题:


  1. 的find()方法返回一个代理,而不是POCO导致Automapper抱怨。我如何获得POCO,而不是代理?

  2. 是进行更新这一最佳做法?


解决方案

如果您使用Automapper这样,它返回一个新病人的对象和对enity框架图中的引用不存。你必须使用这样的:

  [HttpPost]
公众的ActionResult编辑(PatientView视图模型)
{
    病人病人= db.Patients.Find(viewModel.Id)​​;
    Mapper.Map(视图模型,病人);
    ...
    db.SaveChanges();
    返回RedirectToAction(「指数」);
}

I am using EF4 DbContext to provide the model for an ASP.NET MVC app. I use ViewModels to provide data to the views and Automapper to perform the mapping between the EF POCOs and the ViewModels. Automapper does a great job but I'm not clear the best way to use it after the ViewModel is posted back to the controller to carry out an update.

My idea is to get POCO object using a key contained in the ViewModel. I then want to use Automapper to update the POCO with data from the ViewModel:

[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");
}

Two questions:

  1. The Find() method returns a Proxy rather than a POCO which causes Automapper to complain. How do I get the POCO instead of the Proxy?
  2. Is this best practice for performing an update?

解决方案

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

这篇关于使用Automapper更新现有的实体POCO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆