Using automapper to match nested objects

I have an EF POCO class for clients that contains a link to an address table.

The following code seems to work, but I'm not sure if this is the cleanest way to do this. Is there a better way to match this using just one 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); } 
+4
source share
1 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 the properties following this convention:

When you configure a source / destination type pair in AutoMapper, the configurator tries to map the properties and methods to the source, enter the properties in the destination type. If for any property the destination type — the property, method, or method with the “Get” prefix does not exist in the source type, AutoMapper splits the destination member name into separate words (according to PascalCase conventions).

(Source: Flattening )

Then, if CustomerDetailsViewModel has properties:

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

Only one display from Customer to CustomerDetailsViewModel will work. For members who do not comply with this agreement, you can use ForMember .

You can always use ForMember for each property of the same address:

 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 worry too much about calling .Map twice. At the very least, it is very clear that both the Address and Customer properties are displayed.

+14
source

Source: https://habr.com/ru/post/1397133/


All Articles