Search code examples
c#automapper

automapper precondition not working when the condition is not equal to null


I am using the Automapper, and I have fields which sometimes could be null. I want to do some stuff on the value before the Map if the value is not null, so I did this

  .ForMember(dest => dest.PersianEndDate, opt =>
   {
      opt.PreCondition(src => src.EndDate != null);                    
      opt.MapFrom(src => src.EndDate.Value.toShamsi().ToString());
   })

but it doesn't work


Solution

  • you need to do similar to cover the Null value case as well, so your code should be like this:

      .ForMember(dest => dest.PersianEndDate, opt =>
       {
          opt.PreCondition(src => src.EndDate != null);                    
          opt.MapFrom(src => src.EndDate.Value.toShamsi().ToString());
       })
      .ForMember(dest => dest.PersianEndDate, opt =>
       {
          opt.PreCondition(src => src.EndDate == null);                    
          opt.MapFrom(src => DateTime.Now.toShamsi().ToString()); // change this line as you wish, for null case.
       })