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

标签 c# automapper automapper-6

我需要一种方法来向我的自动映射器配置添加舍入。我已尝试按照此处的建议使用 IValueFormatter:Automapper Set Decimals to all be 2 decimals

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

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

使用 AutoMapper 版本 6.11

最佳答案

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

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; }
}

在这里,我们演示一下:

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);
    }
}

预期输出:

1234.46

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

关于c# - 自动映射器舍入所有十进制类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889828/

相关文章:

c# - 在 VS 2015 扩展中,如何在解决方案资源管理器中获取选定的对象?

c# - C# 的内联服务器代码在移动到 JavaScript .js 文件时无法工作

c# - 使用 Automapper 仅映射一个字段

c# - AutoMapper - 将 Json 字符串属性映射到基于接口(interface)的对象

c# - 为什么Automapper会自动将Driver.Name映射到DriverName

c# - AutoMapper.Collections.EntityFramework

c# - 如何使用 Xamarin 的 FFImageLoading 加载本地存储在字节数组中的图像?

c# - 查找虚方法的原始实现

AutoMapper 复杂对象映射 - 映射列表

c# - 使用 AutoMapper 对字符串的枚举描述