I am currently using AutoMapper to map my Entity Framework entities to my View Model:
public class ProductsController : Controller { private IProductRepository productRepository; public ProductsController(IProductRepository productRepository) { this.productRepository = productRepository; } public ActionResult Details(int id) { var product = productRepository.GetProduct(id); if( product == null ) return View("NotFound"); ProductDetailsViewModel model = Mapper.Map<Product, ProductDetailsViewModel>(product); return View(model); } }
This works well. The question I have is when I need to go from my View Model to my entity in order to update the database. Should I be using AutoMapper for this? Is this a bad/dangerous practice?
It seems like AutoMapper is good for flattening a complex type to a simple (flat) type, but so far I'm struggling trying to go from a flat/simple to a more complex type like my entity with the various navigation properties.
If it is a bad idea to use AutoMapper to do this, then what would my code look like for a Create action?
public ActionResult Create(CreateProductViewModel model) { if( ModelState.IsValid ) { // what do i do here to create my Product entity? } }
What about an Edit action?
public ActionResult Edit(int id, EditProductViewModel model) { Product product = productRepository.GetProduct(id); // how do i convert my view model to my entity at this point??? }
AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.
AutoMapper will save you writing a LOT of boring mapping code and it will probably spare you from a few nasty bugs as well. The only thing you must be aware of is that the mapping uses convensions and you really want to follow these. As long as you do that, AutoMapper is a great tool!
Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.
AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.
I'm a of the mindset that updating your entities is a pretty big deal and that no automated tool should ever be used. Set the properties manually.
Yes its a very tiny amount of more code but automapper or running updatemodel on database entities can sometimes have unintended consequences. Better to make sure your writes are done correctly.
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