Cliff Mayson Cliff Mayson - 12 days ago 6
C# Question

AutoMapper with prefix

I'm trying to use Automapper to map to objects, the issue is one of the objects I'm trying to map has a prefix 'Cust_' in front of all its properties and one doesn't. Is there a way to make this mapping.

For example say I have

class A
{
String FirstName { get; set; }
String LastName { get; set; }
}

class B
{
String Cust_FirstName { get; set; }
String Cust_LastName { get; set; }
}


Obviously this map won't work

AutoMapper.Mapper.CreateMap<A, B>();
b = AutoMapper.Mapper.Map<A, B>(a);

Answer
Mapper.Initialize(cfg =>
{
   cfg.RecognizeDestinationPrefixes("Cust_");
   cfg.CreateMap<A, B>();
});

A a = new A() {FirstName = "Cliff", LastName = "Mayson"};
B b = Mapper.Map<A, B>(a);

//b.Cust_FirstName is "Cliff"
//b.Cust_LastName is "Mayson"

Or alternatively:

Mapper.Configuration.RecognizeDestinationPrefixes("Cust_");
Mapper.CreateMap<A, B>();
...
B b = Mapper.Map<A, B>(a);
...
Comments