How to specify mapping rule when names of properties differ Ask Question

How to specify mapping rule when names of properties differ Ask Question

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?

ベストアンサー1

Never mind, I myself found a solution:

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

おすすめ記事