1

I have a class called EmployeeDto which has property FirstName and LastName,

public class EmployeeDto
{
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public string Email { get; set; }
}

While using automapper to convert to employee I want to combine FirstName and LastName and add that to Name field

public class Employee
{
    public string Name { get; set; }
    public string Email { get; set; }
}

How to achieve this?

CuriousGuy
  • 23
  • 3
  • Does this answer your question? [Automapper, mapping single destination property as a concatenation of multiple source property](https://stackoverflow.com/questions/31220501/automapper-mapping-single-destination-property-as-a-concatenation-of-multiple-s) – Sinatr Jun 30 '21 at 14:24
  • What have you tried so far? – Connell.O'Donnell Jun 30 '21 at 14:24

2 Answers2

2

Define an explicit mapping for Name:

CreateMap<EmployeeDto, Employee>()
    .ForMember(
        dest => dest.Name,
        opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));

In the case that FirstName or LastName could be null, it would be tidier to trim the interpolation result:

$"{src.FirstName} {src.LastName}".Trim()
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
1

You can use CreateMap to map FirstName and Lastname to Name

Mapper.CreateMap<EmployeeDto, Employee>()
                        .ForMember(d => d.Name, d => d.MapFrom(x => string.Format("{0}{1}", x.FirstName, x.LastName)));
Amit Kotha
  • 1,641
  • 1
  • 11
  • 16