当源字段不存在时,AutoMapper在目标字段上写入空

时间:2013-04-10 15:38:46

标签: c# automapper

我有以下对象:

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?

1 个答案:

答案 0 :(得分:2)

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

Mapper.Map(api, existing);

然后将映射配置为:

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