我需要一种方法来向我的自动映射器配置添加舍入。我已尝试按照此处的建议使用 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/