AutoMapper Map to different type based on an enum?

血红的双手。 提交于 2019-12-04 09:33:11

Trying to get Necromancer badge.
Nowadays this task can be solved much easier with using ConstructUsing function specifc fields should be filled in the provided action, but all the common fields will go to ForMember execution of the mapping. Collections in this case doesn't requires any additional logic/mapping configurations. Classes that has a property of type collection as well.

cfg.CreateMap<Post, PostModel>()
    .ConstructUsing(p =>
    {
        switch (p.Type)
        {
            case LinkType.Html: return new LinkPostModel
            {
                Title = p.Description
                // other specific fields
            };
            case LinkType.Image: return new ImagePostModel
            {
                // other specific fields
            };
        }
        return null;
    })
    .ForMember(x => x.PostId, m => m.MapFrom(p => p.Id));
cfg.CreateMap<PostList, PostListModel>();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!