19

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);
Myster
  • 17,704
  • 13
  • 64
  • 93
Cliff Mayson
  • 483
  • 5
  • 15

2 Answers2

29
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);
...
Pero P.
  • 25,813
  • 9
  • 61
  • 85
  • 3
    Cheers both methods work perfectly. Although both method don't seem to be specific to the actual map A to B, but will actually effect any other mappings say A to C – Cliff Mayson Feb 17 '12 at 05:11
  • @CliffMayson but I don't think this is problematic, especially in the case where you have multiple target classes following the same convention. In the case where you do truly need to have separate configurations, e.g where you need to have different logic for mapping the same two classes, you can always create dedicated `MappingEngine`s with their own configurations. HTH. – Pero P. Feb 18 '12 at 04:23
1

The documentation has an article on Recognizing pre/postfixes

Sometimes your source/destination properties will have common pre/postfixes that cause you to have to do a bunch of custom member mappings because the names don't match up. To address this, you can recognize pre/postfixes:

public class Source {
    public int frmValue { get; set; }
    public int frmValue2 { get; set; }
}
public class Dest {
    public int Value { get; set; }
    public int Value2 { get; set; }
}
Mapper.Initialize(cfg => {
    cfg.RecognizePrefix("frm");
    cfg.CreateMap<Source, Dest>();
});

Mapper.AssertConfigurationIsValid(); By default AutoMapper recognizes the prefix "Get", if you need to clear the prefix:

Mapper.Initialize(cfg => {
    cfg.ClearPrefixes();
    cfg.RecognizePrefixes("tmp");
});
JJS
  • 6,431
  • 1
  • 54
  • 70