How to specify mapping rule when names of properties differ

We can also specify on Class attributes for mapping

From https://docs.automapper.org/en/stable/Conventions.html#attribute-support

Attribute Support

AddMemberConfiguration().AddName<SourceToDestinationNameMapperAttributesMember>(); * Currently is always on

Looks for instances of SourceToDestinationMapperAttribute for Properties/Fields and calls user defined isMatch function to find member matches.

MapToAttribute is one of them which will match the property based on name provided.

public class Foo
{
    [MapTo("SourceOfBar")]
    public int Bar { get; set; }
}

Considering that we have two classes

public class LookupDetailsBO
    {
        public int ID { get; set; }

        public string Description { get; set; }

    }

and the other class is

public class MaterialBO
    {
        [MapTo(nameof(LookupDetailsBO.ID))]
        public int MaterialId { get; set; }

        [MapTo(nameof(LookupDetailsBO.Description))]
        public string MaterialName { get; set; }

        public int LanguageId { get; set; }
    }

In this way you know typically to which property you follow . and you make sure of the naming convention , so if you have changed the propery name in the source . The MapTo() will prompt an error


Never mind, I myself found a solution:

Mapper.CreateMap<Employee, EmployeeDto>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));

Just to roll the comments above into an updated approach using Automapper 8.1+...

var mapConfig = new MapperConfiguration(
   cfg => cfg.CreateMap<Employee, EmployeeDto>()
      .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
);

Then you would build the mapper using the mapConfig:

var mapper = mapConfig.CreateMapper();

Tags:

C#

Automapper