自动映射器舍入所有十进制类型实例

Don*_*ain 2 c# automapper automapper-6

我需要一种方法来向我的自动映射器配置添加舍入。我尝试按照此处的建议使用 IValueFormatter:Automapper 将小数设置为全部为 2 位小数

但 AutoMapper 不再支持格式化程序。我不需要将其转换为不同的类型,所以我也不确定类型转换器是最好的解决方案。

现在还有一个好的 automapper 解决这个问题吗?

使用 AutoMapper 版本 6.11

小智 5

这是一个完整的 MCVE,演示了如何配置decimalto的映射decimal。在此示例中,我将所有小数值四舍五入为两位数:

public class FooProfile : Profile
{
    public FooProfile()
    {
        CreateMap<decimal, decimal>().ConvertUsing(x=> Math.Round(x,2));
        CreateMap<Foo, Foo>();
    }
}

public class Foo
{
    public decimal X { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们演示一下:

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(x=> x.AddProfile(new FooProfile()));

        var foo = new Foo() { X = 1234.4567M };
        var foo2 = Mapper.Map<Foo>(foo);
        Debug.WriteLine(foo2.X);
    }
}
Run Code Online (Sandbox Code Playgroud)

预期输出:

1234.46

虽然 Automapper 确实知道如何将 a 映射decimaldecimal开箱即用的 a,但我们可以覆盖其默认配置并告诉它如何映射它们以满足我们的需求。