.net 如何配置自动Map器,使其不会覆盖Map中未定义的属性

7cwmlq89  于 2023-02-17  发布在  .NET
关注(0)|答案(1)|浏览(116)

我使用自动Map器将一个类属性与两个不同的其他类进行Map,如下所示:

var emp = map.Map<EmployeeAddressDto, Employee>(employeeAddressDto);

上面的Map为我提供了如下所示的对象:

Address1 = "some xyz address1"
Address2 = "some xyz address2"
Phone = "0000000000"

然后用EmployeeOtherAddressDtoMap输出对象

map.Map<EmployeeOtherAddressDto, Employee>(emp);

上面的Map将my out更改为:

Address1 = "some other xyz address1"
Address2 = "some other xyz address2"
Phone = null

但我希望它像下面这样:

Address1 = "some other xyz address1"
Address2 = "some other xyz address2"
Phone = "0000000000"

当上面的Map发生时,它使phone不为空,但我希望它保持在以前的Map中定义的状态,尽管我希望覆盖Address1Address2字段。
以下是我的Map:

CreateMap<EmployeeAddressDto, Employee>()
                .ForMember(dest => dest.Address1, options => options.MapFrom(src => src.Address1))
                .ForMember(dest => dest.Address2, options => options.MapFrom(src => src.Address2))
                .ForMember(dest => dest.Phone, options => options.MapFrom(src => src.Phone))
                .ValidateMemberList(MemberList.None)
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

CreateMap<EmployeeOtherAddressDto, Employee>()
                .ForMember(dest => dest.Address1, options => options.MapFrom(src => src.Address1))
                .ForMember(dest => dest.Address2, options => options.MapFrom(src => src.Address2))
                .ValidateMemberList(MemberList.None)
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

我想这样做,在我的Map配置文件,因为我正在使用它在许多地方,不想更新手机没有使用Map器。

3vpjnl9f

3vpjnl9f1#

请尝试使用此方法配置Map。
Map后〈〉()

CreateMap<EmployeeOtherAddressDto, Employee>().AfterMap<EmployeeMappingAction>()
                .ForMember(dest => dest.Address1, options => options.MapFrom(src => src.Address1))
                .ForMember(dest => dest.Address2, options => options.MapFrom(src => src.Address2))                    
                .ValidateMemberList(MemberList.None)

你可以在Map后检查你的字段是否为空。

public class EmployeeMappingAction: IMappingAction<EmployeeOtherAddressDto,Employee>
{
    public void Process(EmployeeOtherAddressDto source, Employee destination, ResolutionContext context)
    {
        if (source.Phone == null)
        {
            destination.Phone = "";
        }
    }
}

相关问题