UseDestinationValue only when destination property is not null

試著忘記壹切 提交于 2019-12-01 17:31:17

Had this same problem, but with EF. Cryss' comment about using BeforeMap pointed me in the right direction.

I ended up with code similar to:

In the Configure() method:

Mapper.CreateMap<ItemViewModel, Item>()
           .AfterMap((s, d) => { MapDetailsAction(s, d); })
           .ForMember(dest => dest.Details, opt => opt.UseDestinationValue());

Then the Action:

Action<ItemViewModel, Item> MapDetailsAction = (source, destination) =>
        {
            if (destination.Details == null)
            {
                destination.Details = new Details();
                destination.Details =
                    Mapper.Map<ItemViewModel, Item>(
                    source.Details, destination.Details);
            }
        };

I think the NullSubstitute option would work for you. See: http://weblogs.asp.net/psteele/archive/2011/03/18/automapper-handling-null-members.aspx

EDIT

Looks like you might need to add a little conditional logic to your mapping for Details (and skip the UseDestinationValue option):

.ForMember(d => d.Details, 
    o => o.MapFrom(s => s.Details == null ? new ItemDetails() : Mapper.Map<ItemDetailsViewModel, ItemDetails>(s.Details))

I had this same problem dealing with NHibernate entities and I found quite simple solution to it.

You should initialize the Details property in the ItemViewModel constructor. This way the destination value is not null ever. Of course this does not work in more complex cases (like abstract classes).

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