简体   繁体   English

如何使用 AutoMapper 转换可为 null 的小数?

[英]How do I use AutoMapper to convert a nullable decimal?

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.两个 Field1 都是可为 null 的小数,我希望能够在映射时将值转换为 2 个小数位。 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.无法从用法推断出方法“IPathConfigurationExpression<EntityOne, ModelOne, decimal?>.MapFrom(Expression<Func<EntityOne, TSourceMember>>)”的类型 arguments。 Try specifying the type arguments explicitly.尝试明确指定类型 arguments。

I'm pretty sure you can solve this by just casting the result of Math.Round to a nullable decimal:我很确定您可以通过将Math.Round的结果转换为可为 null 的小数来解决此问题:

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"这样调用应该能够“从用法中推断出来”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM