Automapper map from nested class to single (flatte

2019-03-20 04:28发布

问题:

This is my source:

public class User
{
    public int UserId { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string Address { get; set; }
    public string State {get; set; }
}

This is my destination:

public class UserVM
{
    public int UserId { get; set; }

    public string Address { get; set; }
    public string State { get; set; }
}

How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.

回答1:

If you change your destination class property names to AddressStreet and AddressState, AutoMapper will, by convention, match them to Address.Street and Address.State on the source.

public class UserVM
{
    public int UserId { get; set; }

    public string AddressStreet { get; set; } // User.Address.Street
    public string AddressState { get; set; }  // User.Address.State
}

Alternatively, you leave your destination property names as is and use custom member mappings:

Mapper.CreateMap<User, UserVM>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
    .ForMember(dest => dest.State, opt => opt.MapFrom(src => src.Address.State));

See the AutoMapper documentation for Projection and Flattening for more information.