Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Checking for null in MapFrom

Tags:

c#

automapper

Using version 4

How do I check for null when doing a map. I tried the .Value, but that's not there on a Null:

        Mapper.CreateMap<Agenda, AgendaViewModel>()
            .ForMember(x => x.DateApproved, 
               y => y.MapFrom(s =>  DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc)));
like image 353
Ian Vink Avatar asked Jul 07 '16 05:07

Ian Vink


2 Answers

Alternatively, you can just check the HasValue property prior to mapping:

Mapper.CreateMap<Agenda, AgendaViewModel>()
     .ForMember(x => x.DateApproved,
                y => y.MapFrom(s => s.DateApproved.HasValue ?
                                    DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc) :
                                    DateTime.UtcNow));
like image 89
Will Ray Avatar answered Sep 27 '22 15:09

Will Ray


I think this would work:

Mapper.CreateMap<Agenda, AgendaViewModel>()
        .ForMember(x => x.DateApproved, 
                    y => y.ResolveUsing(z => z.DateApproved.HasValue 
                           ? DateTime.UtcNow :
                           Mapper.Map<Agenda, AgendaViewModel>
                          (DateTime.SpecifyKind(z.DateApproved.Value, DateTimeKind.Utc)));
like image 29
Zein Makki Avatar answered Sep 27 '22 16:09

Zein Makki