Automapper map from one object to nested objects

ⅰ亾dé卋堺 提交于 2019-12-05 12:58:25

For me it was possible to use just MapFrom (without ResolveUsing what gives you a chance to use this mapping with IQueryable extensions). So you will get the following in the Automapper configuration:

Mapper.CreateMap<DTOObject, SubObject>()
    .ForMember(dest => dest.SubPropText, opt => opt.MapFrom(x => x.BottomText))
    .ForMember(dest => dest.SubPropFont, opt => opt.MapFrom(x => x.BottomFont));

Mapper.CreateMap<DTOObject, MainObject>()
    .ForMember(dest => dest.SubPart, opt => opt.MapFrom(x => x));

I ended up creating my own value resolvers for any SubObjects of MainObject that come from DTOObject.

public class PartResolver<T> : ValueResolver<DTOObject, T>
{
    protected override T ResolveCore(DTOObject source)
    {
        return Mapper.Map<T>(source);
    }
}

Then in my Automapper config I create a map from the DTOObject to SubObject and use the ValueResolver to map that object into the MainObject

Mapper.CreateMap<DTOObject, SubObject>();

Mapper.CreateMap<DTOObject, MainObject>()
    .ForMember(dest => dest.SubPart, opt => opt.ResolveUsing<PartResolver<SubObject>>());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!