166
votes

I am a newbie to the Automapper framework. I have a domain class and a DTO class as follows:

public class Employee
{
   public long Id {get;set;}
   public string Name {get;set;}
   public string Phone {get;set;}
   public string Fax {get;set;}
   public DateTime DateOfBirth {get;set;}
}

public class EmployeeDto
{
   public long Id {get;set;}
   public string FullName {get;set;}
   public DateTime DateOfBirth {get;set;}
}

Note: The name of property "Name" of Employee class is not the same as that of property "FullName" of EmployeeDto class.

And here's the code to map the Employee object to EmployeeDto:

Mapper.CreateMap<Employee, EmployeeDto>(); // code line (***)
EmployeeDto dto = Mapper.Map<Employee, EmployeeDto>(employee); 

My question is: If I want to map Employee (source class) to EmployeeDto (destination class), how can I specify the mapping rule? In other words, how should I do more with code line (***) above?

4

4 Answers

328
votes

Never mind, I myself found a solution:

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

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();
6
votes

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; }
}
1
votes

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