Search code examples
c#automappernul

automappewr map null value to destination if source value is zero


Im mapping from a dto to a view model. The dto has a double property, if this value is zero I want to map it as null (this stops infragistics graph plotting a point in case of null, so nothing gets displayed )

I have this but it doesnt work I need it to map to null

.ForMember(x => x.AveragePrice, opt => opt.ResolveUsing(src =>
            {
                if(src.AveragePrice == 0)
                {
                    //need null here
                   return double.NaN;
                }
                else
                {
                    return src.AveragePrice;
                }

            }));

Solution

  • You don't need a resolver. You can use just MapFrom.

    Also make sure that your AveragePrice property is of double? type in your view model.

    .ForMember(x => x.AveragePrice, opt => opt.MapFrom(src => src.AveragePrice == 0 ? (double?)null : Math.Abs(src.AveragePrice)))