I encounter a problem when I try to map DateTime?
to string
,
if source value is null, it will not step in extension method,
do anyone know why?
and I try automapper 10.0 it's normal!
version
Automapper 11.0
.Net6
below is my source code
void Main()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Date,
opt =>opt.MapFrom(src => src.Date.ToCommon()));
});
IMapper mapper = config.CreateMapper();
var source = new Source { Date = null };
var destination = mapper.Map<Destination>(source);
Console.WriteLine(destination.Date);
}
public static class Temp
{
public static string ToCommon(this DateTime? dateTime)
{
if (dateTime is null)
return "something";
return dateTime.Value.ToString("yyyy/MM/dd");
}
}
public class Source
{
public DateTime? Date { get; set; }
}
public class Destination
{
public string Date { get; set; }
}
I expect result should be return "something" ,but return null
AutoMapper for code safety will check the null and won't execute and call a method on null objects. As @dpant mentioned in the comment you can check this issue on the GitHub: https://github.com/AutoMapper/AutoMapper/issues/2409
But I found a trick to make it work:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.Date.ToCommon() ?? ""));
});
IMapper mapper = config.CreateMapper();
var sourceDateNull = new Source { Date = null };
var destinationDateNull = mapper.Map<Destination>(sourceDateNull);
Assert.Equal("something", destinationDateNull.Date);
By above mapping your extension method gets called and will replace something
for null datetimes.