AutoMapper没有更新可空的长?为空

时间:2014-09-13 13:44:59

标签: c# mapping automapper nullable

我有以下两个类:

public class DomainStudent {
    public long Id { get; set; }
    public string AdvisorId { get; set; }
    public long? DegreeId { get; set; }
}

public class ApiStudent {
    public long Id { get; set; }
    public long AdvisorName { get; set; }
    public long? DegreeId { get; set; }
}

当我运行以下映射时:

Mapper.CreateMap<ApiStudent, DomainStudent>();

var api = new ApiStudent();
api.Id = 123;
api.AdvisorName = "Homer Simpson";
api.DegreeId = null;

var domain = new DomainStudent();
domain.Id = 123;
domain.AdvisorName = "Marge Simpson";
domain.DegreeId = 5; // i want this to get written to null

Mapper.Map(api, domain);
// at this point domain.DegreeId = 5 instead of null

我原以为这是默认的。我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

默认情况下,automapper将忽略空源值。

您可以使用以下内容进行更改:

Mapper.Initialize( Conf =>
  {
    Conf.ForSourceType<ApiStudent>().AllowNullDestinationValues = true;
  } );

否则你可以尝试:

Mapper.CreateMap<long?, long?>()
    .ConvertUsing(v => v);

非常丑陋的黑客必须做这样的事情,但它可能有用。

编辑:为了清楚起见,我想注意问题的最终解决方案是upgrading to AutoMapper version 3.2.1