Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: How do I get the name of the destination property

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.

like image 832
Lynel Fernandes Avatar asked Apr 06 '16 16:04

Lynel Fernandes


People also ask

Does AutoMapper map private fields?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Where is AutoMapper configuration?

Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.

How do I ignore source property AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.


1 Answers

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");
like image 195
Arturo Menchaca Avatar answered Oct 13 '22 12:10

Arturo Menchaca