I have a Customers EF POCO class which contains a reference to the Address table.
The following code seems to work, but I’m not sure it’s the cleanest way to do this. Is there a better way to map this using only a single Map call?
[HttpGet]
public ActionResult Details(string ID)
{
BusinessLogic.Customers blCustomers = new BusinessLogic.Customers("CSU");
DataModels.Customer customer = blCustomers.GetCustomer(ID);
CustomerDetailsViewModel model = new CustomerDetailsViewModel();
Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>();
Mapper.CreateMap<DataModels.Address, CustomerDetailsViewModel>();
Mapper.Map(customer, model);
Mapper.Map(customer.Address, model);
return View(model);
}
It depends on what your
CustomerDetailsViewModellooks like. For example, if yourAddressclass looks something like this:and
CustomerDetailsViewModelcontains properties following this convention:(Source: Flattening)
Then, if
CustomerDetailsViewModelhas properties:Just one mapping from
CustomertoCustomerDetailsViewModelwill work. For members that don’t match that convention, you could useForMember.You can always use
ForMemberfor every single address property as well:Personally, I wouldn’t be too worried about calling
.Maptwice. At least that way it’s very clear that bothAddressandCustomerproperties are being mapped.