Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper map from nested class to single (flatten)

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.

like image 922
Shawn Mclean Avatar asked Nov 09 '11 00:11

Shawn Mclean


2 Answers

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.

like image 198
Jeff Ogata Avatar answered Nov 08 '22 14:11

Jeff Ogata


I was stumped by this issue and this solved it for me. I assume in your code, AutoMapper is being injected by your DI container

public class MappingProfile: Profile
{

    public MappingProfile()
    {
        CreateMap<User, UserVM>()
           .IncludeMembers(u => u.Address);
        CreateMap<Address, UserVM>();
    }
}
like image 30
emeka Avatar answered Nov 08 '22 12:11

emeka