Search code examples
c#automapper

How can I do null checks within a lambda expression while using AutoMapper?


I have a mapping profile that looks like this:

public class MappingProfile : Profile {

   public MappingProfile()
   {
       // DTO Mapping
       CreateMap<Animal, AnimalDto>()
        .ForMember(dest => dest.ReceivalDate, opt => opt.MapFrom(src => src.Receival.ReceivalDate));    
   }
}

Now the issue here is I have a Receival as part of the Animal class which can be null at times. However, if I try any of the following I get error:

src.Receival != null ? src.Receival.ReceivalDate : null

Cannot convert lambda expression to type 'IValueResolver<Animal, AnimalDto, object>' because it is not a delegate type

src?.Receival.ReceivalDate

An expression tree lambda may not contain a null propagating operator

Now my question is how can I do null checks withing a lambda expression while using MappingProfiles?


Solution

  • The comment from @zaitsman helped, however, the solution I ended up going with was:

    .ForMember(dest => dest.ReceivalDate, opt => opt.MapFrom(src => (src.Receival != null) ? src.Receival.ReceivalDate : (DateTime?) null))
    

    There reason this worked is because null cannot be used for the Lambda Expression; however, (DateTime?) null did.