Reputation: 10476
I have the following two classes:
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; }
}
When I run the following mapping:
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
I would have thought this worked by default. Am I missing something?
Upvotes: 0
Views: 421
Reputation: 10452
By default automapper will ignore null source values.
You can change this with the following:
Mapper.Initialize( Conf =>
{
Conf.ForSourceType<ApiStudent>().AllowNullDestinationValues = true;
} );
Otherwise you can try:
Mapper.CreateMap<long?, long?>()
.ConvertUsing(v => v);
Pretty ugly hack to have to do something like this but it might work.
edit: Just for clarity I wanted to note the final solution to the question was upgrading to AutoMapper version 3.2.1
Upvotes: 4