使用 ValueTransformer 映射可为 null 和不可为 null 的 double

Mapping nullable and non nullable double using a ValueTransformer

我有一个带有 doubledouble? 的 class,我想在映射过程中舍入这些值。

我创建了一个小代码示例来说明我面临的问题:

当我使用 AddTransform<double?> 时,转换适用于 double? 但对 double 无效。 当我添加 AddTransform<double> 时,只要所有可为空的字段都有值,转换就会起作用。 当添加了两个转换器并且至少有一个字段为空时,我看到以下错误:

AutoMapper.AutoMapperMappingException

Inner Exception 1:
InvalidOperationException: Nullable object must have a value.


Error mapping types.

Mapping types:
TestSource -> TestDestination
AutoMapperValueTransformer.TestSource -> AutoMapperValueTransformer.TestDestination

Type Map configuration:
TestSource -> TestDestination
AutoMapperValueTransformer.TestSource -> AutoMapperValueTransformer.TestDestination

Destination Member:
Prop3


这里是重现问题的代码

using System;

using AutoMapper;

namespace AutoMapperValueTransformer
{
    internal static class Program
    {
        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg => 
                cfg.CreateMap<TestSource, TestDestination>()
                    .AddTransform<double?>(t => t.HasValue ? Math.Round(t.Value, 3) : t)
                    //.AddTransform<double>(t => Math.Round(t, 3))
                    );
            var mapper = config.CreateMapper();

            var src = new TestSource()
            {
                Prop1 = 3.3454353,
                Prop2 = 3.3454353,
                Prop3 = null,
            };

            var dst = mapper.Map<TestSource, TestDestination>(src);

            Console.WriteLine(dst.Prop1);
            Console.WriteLine(dst.Prop2);
            Console.WriteLine(dst.Prop3);
        }
    }

    internal class TestSource
    {
        public double Prop1 { get; set; }

        public double? Prop2 { get; set; }

        public double? Prop3 { get; set; }
    }

    internal class TestDestination
    {
        public double Prop1 { get; set; }

        public double? Prop2 { get; set; }

        public double? Prop3 { get; set; }
    }
}

改用这个:

cfg.CreateMap<double, double>().ConvertUsing(source => Math.Round(source, 3));

或尝试 MyGet 构建。