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:
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).
AutoMapper is a great tool when used for simple conversions. When you start using more complex conversions, AutoMapper can be invaluable. For very simple conversions you could of course write your own conversion method, but why write something that somebody already has written?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With