UseDestinationValue only when destination property is not null

后端 未结 3 1594
不知归路
不知归路 2021-01-18 08:59

How to configure AutoMapper mapping when I want to use behaviour from UseDestinationValue method, but only when destination property is NOT null.

3条回答
  •  悲哀的现实
    2021-01-18 09:53

    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()
               .AfterMap((s, d) => { MapDetailsAction(s, d); })
               .ForMember(dest => dest.Details, opt => opt.UseDestinationValue());
    

    Then the Action:

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

提交回复
热议问题