5

How do I get the name of the destination property:

Public class Source{
    public string FirstName{ get; set; }
}

public class Destination{
    public string C_First_Name{ get; set; }
}

Using AutoMapper, how do i get the name of the destination property when i pass source property Name.

stuartd
  • 70,509
  • 14
  • 132
  • 163

1 Answers1

11

For some map configuration:

var mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, Destination>().ForMember(dst => dst.C_First_Name, opt => opt.MapFrom(src => src.FirstName));
});

You can define a method like this:

public string GetDestinationPropertyFor<TSrc, TDst>(MapperConfiguration mapper, string sourceProperty)
{
    var map = mapper.FindTypeMapFor<TSrc, TDst>();
    var propertyMap = map.GetPropertyMaps().First(pm => pm.SourceMember == typeof(TSrc).GetProperty(sourceProperty));

    return propertyMap.DestinationProperty.Name;
}

Then use it like so:

var destinationName = GetDestinationPropertyFor<Source, Destination>(mapper, "FirstName");
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • No, I dont want mapping. When I pass FirstName, I should be able to get the C_First_Name. Its Name of the Destination property. – Lynel Fernandes Apr 06 '16 at 17:12
  • Sorry, I don't get what are you asking. Can you add an example? – Arturo Menchaca Apr 06 '16 at 17:18
  • Please take a look : http://stackoverflow.com/questions/7561602/automapper-how-to-get-source-property-name-from-propertymap – Lynel Fernandes Apr 06 '16 at 17:32
  • my requirement is very simple : i will pass name of the source property(FirstName) and I want to get the name of the destination property(C_FIrst_Name). Let me know if you have any question. – Lynel Fernandes Apr 06 '16 at 17:33
  • 1
    This post is getting a little old but the question is still valid. Here is another post that is a little more current that addresses the same issue: https://stackoverflow.com/q/53371494/4505594 – JStevens Jan 13 '20 at 15:34