C# AutoMapper Conditional Mapping based upon target value

不羁的心 提交于 2019-12-05 01:42:33

Try this:

Mapper.CreateMap<UserDetails, ProfileViewModel>()
.ForMember(
        destination => destination.Nickname,
        option => 
        {
            option.Condition(rc => 
            {
                var profileViewModel = (ProfileViewModel)rc.InstanceCache.First().Value;
                return profileViewModel.NicknameIsVisible;
            });

            option.MapFrom(source => source.Nickname);
        }
);

Using devduder's example I now have the following code which compiles:

.ForMember(
    destination => destination.Nickname,
    option => 
    {
        option.Condition(resolutionContext =>
            (resolutionContext.InstanceCache.First().Value as ProfileViewModel).NicknameIsVisible);
        option.MapFrom(source => source.Nickname);
    }
);

However although it compiles and runs through it is not populating the destination.Nickname with anything.

Edit: I had to change the order of my mapping so the preferences object (which has the values for the "NicknameIsVisible" property was mapped first so the value was available to test against!)

So the call to my three-way mapping was:

var profileViewModel = EntityMapper.Map<ProfileViewModel>(preferences, member, account);

This ensured that the preferences object was mapped to the ViewModel first, then the conditional mapping for the account object could take place once the values had been set.

So this is my solution, but I cannot up-vote my own answer!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!