Ramppy Dumppy
Ramppy Dumppy

Reputation: 2817

Mapping list in automapper

I am new to automapper. I have a class that has a collection of object. And I need that class to map to another object that has a different name. I need to map the employee to employeeDto. Both classes has different name and different propery name. Can they be mapped using automapper if they have a different name?

public class Employee
{
    public string Name { get; set; }
    public string Address { get; set; }
    public List<Job> Jobs { get; set; }
}
public class Job
{
    public string CompanyName { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

public class EmployeeDto
{
    public string Fullname { get; set; }
    public string Location { get; set; }
    public List<WorkExperience> WorkExperience { get; set; }
}
public class WorkExperience
{
    public string NameOfCompany { get; set; }
    public DateTime DateBegin { get; set; }
    public DateTime DateEnd { get; set; }
}

Upvotes: 0

Views: 224

Answers (1)

dlxeon
dlxeon

Reputation: 2000

You can configure mapping to handle you Jobs list to WorkExperience list manually. See Projection section in AutoMapper documentation

AutoMapper.Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Employee, EmployeeDto>()
    .ForMember(dest => dest.Fullname, opt => opt.MapFrom(src => src.Name))
    .ForMember(dest => dest.Location, opt => opt.MapFrom(src => src.Address))
    .ForMember(dest => dest.WorkExperience, opt => opt.MapFrom(src => src.Jobs));

    cfg.CreateMap<Job, WorkExperience>()
    .ForMember(dest => dest.NameOfCompany, opt => opt.MapFrom(src => src.CompanyName))
    .ForMember(dest => dest.DateBegin, opt => opt.MapFrom(src => src.StartDate))
    .ForMember(dest => dest.DateEnd, opt => opt.MapFrom(src => src.EndDate));
});

Additionally, if you want to convert in the opposite direction, you can add ReverseMap() to avoid code duplication.

Upvotes: 4

Related Questions