2

I need a way to add rounding to my automapper configuration. I have tried using the IValueFormatter as suggested here: Automapper Set Decimals to all be 2 decimals

But AutoMapper no longer supports formatters. I don't need to covert it to a different type, so I'm not sure a type converter is the best solution either.

Is there still a good automapper solution for this problem now?

Using AutoMapper version 6.11

Don Sartain
  • 557
  • 9
  • 25
  • See https://stackoverflow.com/questions/30137734/whats-the-alternative-to-ivalueformatter-in-automapper –  Dec 19 '17 at 15:07
  • The problem with that solution is that means I have to go through and find every decimal type instance. I want to do this by decimal type, not by property. – Don Sartain Dec 19 '17 at 15:15
  • Just create a map from decimal to decimal and apply that formatter. You don't need to do it everywhere. Just tell automapper how to map decimals to decimals. –  Dec 19 '17 at 15:16

2 Answers2

5

This is a complete MCVE demonstrating how you can configure the mapping of decimal to decimal. In this example I round all decimal values to two digits:

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

Here, we demonstrate it:

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

Expected output:

1234.46

While its true that Automapper knows how to map a decimal to a decimal out of the box, we can override its default configuration and tell it how to map them to suit our needs.

0

The answer provided above is correct. Just wanted to point out that we can also achieve this using AutoMapper's MapperConfiguration as well, instead of Profiles.

We can modify the above code to use MapperConfiguration as follows.

Define the Foo class

public class Foo
{
        public decimal X { get; set; }
}

Modify the main method as follows:

class Program
{
    private IMapper _mapper;

    static void Main(string[] args)
    {
        InitialiseMapper();

        var foo = new Foo() { X = 1234.4567M };
        var foo2 = _mapper.Map<Foo>(foo);
        Debug.WriteLine(foo2.X);
    }

    private void InitialiseMapper()
    {
        var mapperConfig = new MapperConfiguration(cfg =>
            {
                CreateMap<decimal, decimal>().ConvertUsing(x=> Math.Round(x,2));
                CreateMap<Foo, Foo>();                   
            });

            _mapper = mapperConfig.CreateMapper();            
    }
}
j4jada
  • 334
  • 1
  • 9