我有以下对象:
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?
答案 0 :(得分:2)
您必须将Map()调用更改为:
Mapper.Map(api, existing);
然后将映射配置为:
Mapper.CreateMap<ApiStudent, DomainStudent>()
.ForMember(dest => dest.AdvisorId, opt => opt.Ignore());