Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using automapper to map nested objects

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);
    }
like image 516
Scottie Avatar asked Dec 10 '22 02:12

Scottie


1 Answers

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.

like image 114
Andrew Whitaker Avatar answered Dec 25 '22 13:12

Andrew Whitaker