0

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

New contributor
lin kuanfu is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 1
    This behavior of MapFrom is discussed here. Simply put, AutoMapper automatically checks for null and does not execute MapFrom when value is null.
    – dpant
    Commented Jul 6 at 6:27

1 Answer 1

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.