Automapper map into nested class

前端 未结 3 363
抹茶落季
抹茶落季 2020-12-14 18:56

I have 1 class that I need t map into multiple classes, for eg.

This is the source that I\'m mapping from(view model):

public class UserBM
{
    publ         


        
相关标签:
3条回答
  • 2020-12-14 19:20

    I'm using Automapper 9 and the answers above didn't work for me. Then for resolve my problem that is like yours I use .afterMap, like that:

    public class AutoMapperUser : Profile
    {
            public AutoMapperUser ()
            {
                CreateMap<UserBM, User>()
                    .AfterMap((src, dest, context) => dest.Location = context.Mapper.Map<UserBM, Location>(src));
            }
        }
    }
    

    I hope to help somebody.

    0 讨论(0)
  • 2020-12-14 19:35

    I have another solution. The main idea is that AutoMapper know how to flatten nested objects when you name properly properties in flattened object: adding nested object property name as a prefix. For your case Location is prefix:

    public class UserBM
    {
        public int UserId { get; set; }
    
        public int LocationId { get; set; }
        public string LocationAddress { get; set; }
        public string LocationState { get; set; }
        public string LocationCountry { get; set; }
        ...
    }
    

    So creating familiar mapping from nested to flattened and then using ReverseMap method allows AutomMapper to understand how to unflatten nested object.

    CreateMap<UserBM, User>()
       .ReverseMap();
    

    That's all!

    0 讨论(0)
  • 2020-12-14 19:36

    Define two mappings, both mapping from the same source to different destinations. In the User mapping, map the Location property manually using Mapper.Map<UserBM, Location>(...)

    Mapper.CreateMap<UserBM, Location>();
    Mapper.CreateMap<UserBM, User>()
        .ForMember(dest => dest.Location, opt => 
             opt.MapFrom(src => Mapper.Map<UserBM, Location>(src));
    
    0 讨论(0)
提交回复
热议问题