5

Trying to automap some objects.
Source objects has properties with _ before name, destination objects - have not. Is it possible to implement ONE map creation, that automapper would map all _properties to properties
for all source types.

class MyMapper<TFrom, TTo>{
    TTo PerformMap(TFrom fromObject){
        Mapper.CreateMap<From, To>(); // ???
        TTo result = Mapper.Map<From, To>(fromObject);
        //result.Id.ShouldBe(value from TFrom._Id);
        return result;
    }
}

class From
{
    public int _Id { get; set; }
    public string _Name { get; set; }
}

class To
{
    public int Id { get; set; }
    public string Name { get; set; }
}
womp
  • 115,835
  • 26
  • 236
  • 269
Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195

3 Answers3

9

Something I added recently to AutoMapper might help you - custom naming conventions. If you check out the trunk (R107), look around for INamingConvention. Right now, I have two naming conventions (PascalCase and lower_case_underscore), but it's really just a matter of figuring out the right RegEx to get you going:

INamingConvention.cs

Right now, naming conventions are global and profile-scoped. Since this feature is new, there isn't any documentation other than the tests.

Jim W
  • 3
  • 3
Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69
  • I'm not using AM at the moment, but nice to know about this feature. :) – Arnis Lapsa Aug 02 '09 at 08:16
  • 1
    the link in this answer gives a 404, can you please update? Thanks for the awesome work Jimmy! – shanabus Feb 15 '12 at 16:29
  • Does this work with IDataReader sources? I am trying to map DataTable in lower_case_underscore to an object w/ properties in PascalCase but can't seem to get it to work. – Merritt Mar 27 '15 at 14:45
2

This is how I'm doing it

Mapper.Initialize(cfg =>
        {
            cfg.RecognizeDestinationPrefixes(new []{"_"});
            cfg.RecognizePrefixes(new[] { "_" });

            cfg.CreateMap<To, From>().ReverseMap();
        });
Halter
  • 48
  • 2
  • 6
  • 30
0

For this you could add a custom mapping to solve this particular case:

Mapper.CreateMap<From, To>()
   .ForMember( dest => dest.Id, opt => opt.MapFrom( src => src._Id ) )
   .ForMember( dest => dest.Name, opt => opt.MapFrom( src => src._Name ) );
MotoWilliams
  • 1,538
  • 1
  • 12
  • 22
  • That`s the effect i need, but... I wanted that to be more generic. Like saying - automapper, map those 2 objects, and ignore underscore of prop name, if it`s first symbol in name. Otherwise - i have to pay attention for all object pairs. – Arnis Lapsa Apr 29 '09 at 07:59
  • This is unrealistic in real-world applications where there are potentially hundreds of POCOs – Captain Kenpachi Mar 08 '19 at 11:04