仅在目标值为null时映射

问题描述

我是automapper的新手,仅当目标值为null时,我才尝试映射。我检查了文档,但它仅显示源值的条件。我可以知道如何在条件下检查目标值吗?

this.CreateMap<DtoObject,MyObject>()
                .EqualityComparison((dto,o) =>
                    dto.id== o.id)
                    .ForMember(s => s.MyField,opt =>
                    {
                    
//I want to Map only MyField of destination object is null,otherwise I don't want to map. But How can I get destination's MyField value?
                   
        });

解决方法

有两种方法可以达到这种效果。

首选方法是使用Automapper conditional Mapping

        CreateMap<DtoObject,MyObject>()
            .ForMember(dest => dest.MyField,opt =>
            {
                opt.PreCondition((source,dest,ctx) => dest.MyField == null);
                opt.MapFrom(src => src.MyField);
            });

另一种方法是在映射过程中结合使用AfterMap方法和Ignore,就像这样。

        CreateMap<DtoObject,MyObject>()
            .ForMember(d => d.MyField,a => a.Ignore())
            .AfterMap((source,destination) =>
            {
                if (destination.MyField == null)
                {
                    destination.Name = source.MyField;
                }
            });

这将告诉AutoMapper在映射过程中忽略该属性,并在后续映射期间执行一些自定义逻辑。

,

看看AutoMapper Conditional mapping

使用PreCondition可以访问sourcedestination并设置应映射属性的条件:

this.CreateMap<DtoObject,MyObject>()
            .EqualityComparison((dto,o) =>
                dto.id== o.id)
                .ForMember(s => s.MyField,opt =>
                {
                    opt.PreCondition((dest,src) => dest.SomeDestinationProperty == null);
                    opt.MapFrom(src => src.SomeSourceProperty);
                });