Automapper is used to map nested items. automapper entity-framework


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?

    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);
2/17/2012 11:56:27 PM

Accepted Answer

It depends on what your CustomerDetailsViewModel looks like. For example, if your Address class looks something like this:

public class Address 
    public string Street { get; set; }
    public string City { get; set; }

and CustomerDetailsViewModel contains properties following this convention:

When you configure a source/destination type pair in AutoMapper, the configurator attempts to match properties and methods on the source type to properties on the destination type. If for any property on the destination type a property, method, or a method prefixed with "Get" does not exist on the source type, AutoMapper splits the destination member name into individual words (by PascalCase conventions).

(Source: Flattening)

Then, if CustomerDetailsViewModel has properties:

public string AddressStreet { get; set; }
public string AddressCity { get; set; }

Just one mapping from Customer to CustomerDetailsViewModel will work. For members that don't match that convention, you could use ForMember.

You can always use ForMember for every single address property as well:

Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street));
    /* etc, for other address properties */

Personally, I wouldn't be too worried about calling .Map twice. At least that way it's very clear that both Address and Customer properties are being mapped.

2/18/2012 3:43:15 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow