Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
569 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...