automapper conversion from decimal to bool if not null

849 views Asked by At

I am trying to convert from bool value to decimal i automapper. It works fine if i dont check for null values .But i want to check for null values and if the value is null ,let the value be null i destination else convert to decimal.Below is the ode i tied but i am getting a error.

  cfg.CreateMap<sourcemodel, destinatiomodel>()    
     .ForMember(dest =>  dest.WorkhoursPerWeek != null ? 
                Convert.ToDecimal(dest.WorkhoursPerWeek) : null, 
                opts => opts.MapFrom(src => src.cstu_WorkHoursPerWeek));
1

There are 1 answers

5
Erik Philips On

You code doesn't make sense (mainly because it's invalid). If you need to check the source property first, I'd suggest using AfterMap()

cfg.CreateMap<sourcemodel, destinatiomodel>()    
  .AfterMap((src, dest) =>  
    {
      dest = dest.WorkhoursPerWeek != null 
      ? Convert.ToDecimal(dest.WorkhoursPerWeek) 
      : src.cstu_WorkHoursPerWeek
    });

(Or this might not work, and if not, use BeforeMap() to map before and Ignore() the property).