Home > Enterprise >  How do I use AutoMapper to convert a nullable decimal?
How do I use AutoMapper to convert a nullable decimal?

Time:01-11

So my code appears as:

CreateMap<EntityOne, ModelOne>()
.ForPath(dest => dest.Field1, opt => opt.MapFrom(src => src.Field1))

Both Field1 are nullable decimals, I want to be able to convert the value to 2 decimal places as I'm mapping. Think my best attempt has been:

CreateMap<EntityOne, ModelOne>()
                .ForPath(dest => dest.Field1, opt => opt.MapFrom(src => src.Field1.HasValue ? Math.Round((decimal)src.Field1, 2, MidpointRounding.AwayFromZero) : null))

The error I get is:

The type arguments for method 'IPathConfigurationExpression<EntityOne, ModelOne, decimal?>.MapFrom(Expression<Func<EntityOne, TSourceMember>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

CodePudding user response:

I'm pretty sure you can solve this by just casting the result of Math.Round to a nullable decimal:

opt.MapFrom(src => src.Field1.HasValue 
         ? (decimal?)Math.Round((decimal)src.Field1, 2, MidpointRounding.AwayFromZero) 
         : null)

This way the call should be able to be "inferred from the usage"

  • Related