Automapper:在MapFrom中检查null

时间:2016-07-07 05:10:59

标签: c# automapper

使用版本4

在执行地图时如何检查null。我尝试了.Value,但那不是Null:

        Mapper.CreateMap<Agenda, AgendaViewModel>()
            .ForMember(x => x.DateApproved, 
               y => y.MapFrom(s =>  DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc)));

2 个答案:

答案 0 :(得分:5)

或者,您可以在映射之前检查HasValue属性:

Mapper.CreateMap<Agenda, AgendaViewModel>()
     .ForMember(x => x.DateApproved,
                y => y.MapFrom(s => s.DateApproved.HasValue ?
                                    DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc) :
                                    DateTime.UtcNow));

答案 1 :(得分:2)

我认为这样可行:

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)));