1

I have a number of objects that all have a CreatedDt property. Each of these objects needs to be mapped to a matching DTO that has a Created_dt property.

Using AutoMapper, how do I set up a generic configuration to map CreatedDt to Created_dt (and vise versa) without having to do it manually for each map?

Andrew
  • 893
  • 12
  • 28
  • [This](http://stackoverflow.com/questions/31706697/custom-mapping-with-automapper) might point you in the right direction, but I think it will be 100x more problematic than what is solves. – Scott Hannen May 18 '17 at 00:49

1 Answers1

1

There is a lot of ways to achieve this result:

Naming conventions, e.g.: this

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<A, ADto>();
            cfg.AddMemberConfiguration()
                .AddName<ReplaceName>(_ => _.AddReplace(nameof(A.CreateDate), nameof(ADto.Created_dt)));
        });

        var mapper = config.CreateMapper();

        var a = new A { CreateDate = DateTime.UtcNow, X = "X" };
        var aDto = mapper.Map<ADto>(a);
    }
}

public class A
{
    public DateTime CreateDate { get; set; }

    public string X { get; set; }
}

public class ADto
{
    public DateTime Created_dt { get; set; }
    public string X { get; set; }
}

Attributes (add this attribute in your base class which has CreatedDt property):

 public class Foo
 {
     [MapTo("Created_dt")]
     public int CreatedDt { get; set; }
 }

Default mapping configuration (AutoMapper Defaults).

Community
  • 1
  • 1
Pawel Maga
  • 5,428
  • 3
  • 38
  • 62
  • Thanks @Pawel. Do you think you could provide an example of option number one or three above? – Andrew May 18 '17 at 23:07
  • I've added example how you can achieve something like that by using ReplaceName convention. I've checked your case and AutoMapper should be able to map from Pascal case to Snake case by default and no additional configuration is required. – Pawel Maga May 19 '17 at 14:08
  • I'm seeing weird behaviour. By default convention, automapper is automatically going from CreatedDt to Created_dt, but fails to properly go the other way from Created_dt to CreatedDt. I'm not sure why that is happening. Thank you for providing the example. – Andrew May 19 '17 at 15:07