当源字段不存在时,AutoMapper将目标字段写入Null

本文关键字:字段 目标 Null 不存在 AutoMapper | 更新日期: 2023-09-27 18:08:34

我有以下对象:

public class DomainStudent {
    public long Id { get; set; }
    public string AdvisorId { get; set; }
}
public class ApiStudent {
    public long Id { get; set; }
    public long AdvisorName { get; set; }
}

当我运行以下映射时:

ApiStudent api = new ApiStudent();
api.Id = 123;
api.AdvisorName = "Homer Simpson";
DomainStudent existing = service.load(api.Id); // 123
// at this point existing.AdvisorId = 555
existing = Mapper.Map<ApiStudent, DomainStudent>(api);
// at this point existing.AdvisorId = null

我如何配置AutoMapper,这样当属性AdvisorId从源对象中缺失时,它不会被覆盖为null?

当源字段不存在时,AutoMapper将目标字段写入Null

必须将Map()调用更改为:

Mapper.Map(api, existing);

,然后配置映射为:

 Mapper.CreateMap<ApiStudent, DomainStudent>()
            .ForMember(dest => dest.AdvisorId, opt => opt.Ignore());