Using automapper to map nested objects

北慕城南 提交于 2019-12-13 13:25:48

问题


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);
    }

回答1:


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.



来源:https://stackoverflow.com/questions/9337098/using-automapper-to-map-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!